I am creating a C# forms application, a gradebook in particular everything is fine except I keep getting this error : cannot convert type string into int


Here is my code

// Fig. 18.9: CreateFileForm.cs
  // Creating a sequential-access file.
  using System;
  using System.Windows.Forms;
  using System.IO;
  using GradeBook;

  public partial class CreateFileForm : Form 
  {
     private StreamWriter fileWriter;
     private Button saveButton;
     private Button enterButton;
     private TextBox lastNametextBox;
     private TextBox firstNametextBox;
     private TextBox gradetextBox;
     private TextBox classtextBox;
     private TextBox iDNumbertextBox;
     private Label label1;
     private Label label2;
     private Label label3;
     private Label label4;
     private Label label5;
     private Button button1; // writes data to text file
     private FileStream output; // maintains connection to file  

     // enumeration constants specify TextBox indices
     public enum TextBoxIndices
     {
         LAST,
         FIRST,
         ID,
         CLASS,
         GRADE,
     } // end enum

     // parameterless constructor
     public CreateFileForm()
     {
        InitializeComponent();
     } // end constructor



     // clear all TextBoxes
     public void ClearTextBoxes()
     {
         // iterate through every Control on form
         for (int i = 0; i < Controls.Count; i++)
         {
             Control myControl = Controls[i]; // get control

             // determine whether Control is TextBox
             if (myControl is TextBox)
             {
                 // clear Text property ( set to empty string )
                 myControl.Text = "";
             } // end if
         } // end for
     } // end method ClearTextBoxes

     // event handler for Save Button
     private void saveButton_Click( object sender, EventArgs e )
     {
        // create dialog box enabling user to save file
        SaveFileDialog fileChooser = new SaveFileDialog();
        DialogResult result = fileChooser.ShowDialog();   
        string fileName; // name of file to save data

        fileChooser.CheckFileExists = false; // allow user to create file

        // exit event handler if user clicked "Cancel"
        if ( result == DialogResult.Cancel )
           return;

        fileName = fileChooser.FileName; // get specified file name

        // show error if user specified invalid file
        if ( fileName == "" || fileName == null )
           MessageBox.Show( "Invalid File Name", "Error",
              MessageBoxButtons.OK, MessageBoxIcon.Error );
        else
        {
           // save file via FileStream if user specified valid file
           try
          {
              // open file with write access
             output = new FileStream( fileName,           
                 FileMode.OpenOrCreate, FileAccess.Write );

             // sets file to where data is written
             fileWriter = new StreamWriter( output );

             // disable Save button and enable Enter button
              saveButton.Enabled = false;
              enterButton.Enabled = true;
          } // end try
           // handle exception if there is a problem opening the file
          catch ( IOException )
           {
              // notify user if file does not exist
              MessageBox.Show( "Error opening file", "Error",
                 MessageBoxButtons.OK, MessageBoxIcon.Error );
          } // end catch
        } // end else
     } // end method saveButton_Click






     // handler for enterButton Click
     private void enterButton_Click( object sender, EventArgs e )
     {
        // store TextBox values string array
        string[] values = GetTextBoxValues();

        // Record containing TextBox values to serialize
        Record record = new Record();

        // determine whether TextBox account field is empty
        if ( values[ ( int ) TextBoxIndices.ID ] != "" )
        {
           // store TextBox values in Record and serialize Record
           try
           {
             // get account number value from TextBox
              int accountNumber = Int32.Parse(
                 values[ ( int ) TextBoxIndices.ID ] );

              // determine whether accountNumber is valid
              if ( accountNumber > 0 )
              {
                // store TextBox fields in Record


                  record.LastName = values[(int)TextBoxIndices.LAST];

                  record.FirstName = values[(int)TextBoxIndices.FIRST];

                  record.iDNumber = values[(int)TextBoxIndices.ID];

                 record.ClassName = values[(int)TextBoxIndices.CLASS]; error is here

                  record.Grade  = values[(int)TextBoxIndices.GRADE];



             // write Record to file, fields separated by commas
                 fileWriter.WriteLine(     
                     
    record.LastName + record.FirstName +  record.iDNumber + 
    record.ClassName  + record.Grade );

              } // end if
              else
             {
                // notify user if invalid account number
                MessageBox.Show( "Invalid Account Number", "Error",
                   MessageBoxButtons.OK, MessageBoxIcon.Error );
             } // end else
          } // end try
          // notify user if error occurs in serialization
          catch ( IOException )
         {
             MessageBox.Show( "Error Writing to File", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error );
          } // end catch
          // notify user if error occurs regarding parameter format
          catch ( FormatException )
          {
            MessageBox.Show( "Invalid Format", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error );
          } // end catch
       } // end if

       ClearTextBoxes(); // clear TextBox values
    }

     private string[] GetTextBoxValues()
     {
         throw new NotImplementedException();
     } // end method enterButton_Click

    // handler for exitButton Click
    private void exitButton_Click( object sender, EventArgs e )
    {
       // determine whether file exists
       if ( output != null )
       {
          try
         {
            fileWriter.Close(); // close StreamWriter
             output.Close(); // close file
          } // end try
          // notify user of error closing file
          catch ( IOException )
          {
             MessageBox.Show( "Cannot close file", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error );
          } // end catch
       } // end if

       Application.Exit();
    }

    private void InitializeComponent()
    {
        this.saveButton = new System.Windows.Forms.Button();
        this.enterButton = new System.Windows.Forms.Button();
        this.lastNametextBox = new System.Windows.Forms.TextBox();
        this.firstNametextBox = new System.Windows.Forms.TextBox();
        this.gradetextBox = new System.Windows.Forms.TextBox();
        this.classtextBox = new System.Windows.Forms.TextBox();
        this.iDNumbertextBox = new System.Windows.Forms.TextBox();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.label5 = new System.Windows.Forms.Label();
        this.button1 = new System.Windows.Forms.Button();
        this.SuspendLayout();
        // 
        // saveButton
        // 
        this.saveButton.Location = new System.Drawing.Point(148, 119);
        this.saveButton.Name = "saveButton";
        this.saveButton.Size = new System.Drawing.Size(75, 23);
        this.saveButton.TabIndex = 0;
        this.saveButton.Text = "SAVE AS";
        this.saveButton.UseVisualStyleBackColor = true;
        // 
        // enterButton
        // 
        this.enterButton.Location = new System.Drawing.Point(261, 119);
        this.enterButton.Name = "enterButton";
        this.enterButton.Size = new System.Drawing.Size(75, 23);
        this.enterButton.TabIndex = 1;
        this.enterButton.Text = "ENTER";
        this.enterButton.UseVisualStyleBackColor = true;
        // 
        // lastNametextBox
        // 
        this.lastNametextBox.Location = new System.Drawing.Point(26, 50);
        this.lastNametextBox.Name = "lastNametextBox";
        this.lastNametextBox.Size = new System.Drawing.Size(100, 20);
        this.lastNametextBox.TabIndex = 2;
        // 
        // firstNametextBox
        // 
        this.firstNametextBox.Location = new System.Drawing.Point(169, 50);
        this.firstNametextBox.Name = "firstNametextBox";
        this.firstNametextBox.Size = new System.Drawing.Size(100, 20);
        this.firstNametextBox.TabIndex = 3;
        // 
        // gradetextBox
        // 
        this.gradetextBox.Location = new System.Drawing.Point(541, 50);
        this.gradetextBox.Name = "gradetextBox";
        this.gradetextBox.Size = new System.Drawing.Size(100, 20);
        this.gradetextBox.TabIndex = 4;
        // 
        // classtextBox
        // 
        this.classtextBox.Location = new System.Drawing.Point(435, 50);
        this.classtextBox.Name = "classtextBox";
        this.classtextBox.Size = new System.Drawing.Size(100, 20);
        this.classtextBox.TabIndex = 5;
        // 
        // iDNumbertextBox
        // 
        this.iDNumbertextBox.Location = new System.Drawing.Point(302, 50);
        this.iDNumbertextBox.Name = "iDNumbertextBox";
        this.iDNumbertextBox.Size = new System.Drawing.Size(100, 20);
        this.iDNumbertextBox.TabIndex = 6;
        // 
        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(23, 9);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(58, 13);
        this.label1.TabIndex = 7;
        this.label1.Text = "Last Name";
        // 
        // label2
        // 
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(166, 9);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(57, 13);
        this.label2.TabIndex = 8;
        this.label2.Text = "First Name";
        // 
        // label3
        // 
        this.label3.AutoSize = true;
        this.label3.Location = new System.Drawing.Point(308, 9);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(28, 13);
        this.label3.TabIndex = 9;
        this.label3.Text = "ID #";
        // 
        // label4
        // 
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(432, 9);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(32, 13);
        this.label4.TabIndex = 10;
        this.label4.Text = "Class";
        // 
        // label5
        // 
        this.label5.AutoSize = true;
        this.label5.Location = new System.Drawing.Point(547, 9);
        this.label5.Name = "label5";
        this.label5.Size = new System.Drawing.Size(36, 13);
        this.label5.TabIndex = 11;
        this.label5.Text = "Grade";
        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(370, 119);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 12;
        this.button1.Text = "EXIT";
        this.button1.UseVisualStyleBackColor = true;
        // 
        // CreateFileForm
        // 
        this.ClientSize = new System.Drawing.Size(647, 264);
        this.Controls.Add(this.button1);
        this.Controls.Add(this.label5);
        this.Controls.Add(this.label4);
        this.Controls.Add(this.label3);
        this.Controls.Add(this.label2);
        this.Controls.Add(this.label1);
        this.Controls.Add(this.iDNumbertextBox);
        this.Controls.Add(this.classtextBox);
        this.Controls.Add(this.gradetextBox);
        this.Controls.Add(this.firstNametextBox);
        this.Controls.Add(this.lastNametextBox);
        this.Controls.Add(this.enterButton);
        this.Controls.Add(this.saveButton);
        this.Name = "CreateFileForm";
        this.ResumeLayout(false);
        this.PerformLayout();

    } // end method exitButton_Click
 } // end class CreateFileForm

Recommended Answers

All 15 Replies

Where is the definition of Record?

here it is

// Fig. 19.8: Record.cs
// Class that represents a data record.

namespace GradeBook
{
   public class Record
   {
      
    
      // auto-implemented LastName property
      public string LastName { get; set; }

      // auto-implemented FirstName property
      public string FirstName { get; set; }

      // auto-implemented iDNumber property
      public int iDNumber { get; set; }


      // auto-implemented Class property
      public string ClassName { get; set; }

      // auto-implemented Grade property
      public string Grade { get; set; }


      // parameterless constructor sets members to default values
      public Record()
         : this( 0, string.Empty, string.Empty, 0M )
      {
      } // end constructor

      // overloaded constructor sets members to parameter values
      public Record( string lastNameValue, string firstNameValue,
         string classNameValue, int iDNumberValue, string gradeNameValue)
      {
       
         
         LastName = lastNameValue;
         FirstName = firstNameValue;
         ClassName = classNameValue;
         iDNumber = iDNumberValue;
         Grade = gradeNameValue;


      } // end constructor
   } // end class Record
} // end namespace BankLibrary

I also have one last error that says Gradebook.record does not contain a constructor that takes four arguments.

Can you zip and post the file. I've done some testing but can't get anything to create an error so I'd like to see what happens when I have everything :)

Seen this post before. It makes no sense to post a million lines of code and than stating there is an error in it.
If you would have posted code with proper code tags, they would have line numbers.
So I have only this, to copy and paste a part of your code:

// parameterless constructor sets members to default values
      public Record()
         : this( 0, string.Empty, string.Empty, 0M )
      {
      } // end constructor

This code calls a parameterless constructor, which in turn calls a constructor who needs 4 (YES FOUR!) parameters, the first one being an integer 0, folowed by a string and yet another string String.Empty, the last parameter is a decimal value 0M
Because, in your code you have not defined such a constructor, you get the error. Also defining another constructor with 5 (YES FIVE!) parameters will not resolve the problem. Please try to work that out.

I don't know if I understand (don't want to read whole code) but you want to convert string to int to get array element

record.ClassName = values[(int)TextBoxIndices.CLASS];

I think you should do it that way

record.ClassName = values[int.Parse(TextBoxIndices.CLASS)];

record.ClassName = values[int.Parse(TextBoxIndices.CLASS)]; still doesnt work it passes of another error. Error2:The best overloaded method match for 'int.Parse(string)' has some invalid arguments

That's because his post is entirely wrong. He didn't bother to look at the types in the statement at all.

I've red just a line with error and then made simple program

string a = "234";
int b = (int)a;

and of course it doesn't work (compile), because it should be

int b =  int.Parse(a);

Now I downloaded his code and I can see some other problems. Didn't even get to this one what he mentioned

Now I can see.

record.iDNumber   = int.Parse(values[(int)TextBoxIndices.ID]);

There are 11 errors when I try to compile the code.

Record.cs - Line 29. You are attempting to call a constructor that requires parameters from the parameterless constructor, but you don't provide enough parameters. My best guess at what this should be is:

public Record() : this( String.Empty, String.Empty, String.Empty, 0, String.Empty)

The exact same problem occurs in RecordSerializeable.

In CreateFileForm there is no method GetTextBoxValues or ClearTextBoxes. The enum TextBoxIndices also does not exit.

The error you mention does not appear at all. Fix these errors first.

What I think is happening here, is you are trying to make a gradebook program. Good!
You found some code to handle banking (see the variables named accountnumber the use of the decimal type...) You thought a banking account and a grade are practically the same, so lets do a "quick" change... This is a SURE way to disaster as you can see for yourself.
My suggestion: throw everything away and start from scratch!
Do not copy and paste but type it all back in!
This may be hard I know, but in the end it will be quicker!
Believe me I had experience in this!

I got it I made one from scratch with some help form a_lan thanks for the advice am new at this but am getting the ropes

I'm glad you got your problem worked out, but you shouldn't do it in private messages. What good does you fixing your problem if others can't see how it was done? That is kind of the point of the forums, so others can see the solution to problems so they can fix their code when they encounter the same or similar problem.

commented: Very good point! +8

Here is the code

namespace GradeBook
{	
	public partial class Form1 : Form
	{
		//private string filename;
		//private bool loaded;

		public Form1()
		{
			InitializeComponent();
			//loaded = false;
		}

		private void button1_Click(object sender, EventArgs e)
		{
			if (openFileDialog1.ShowDialog() == DialogResult.OK)
			{
				try
				{
					using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
					{
						string line;

						tb_list.Text = string.Empty;

						while ((line = sr.ReadLine()) != null)
						{
							tb_list.Text += line +"\r\n";
						}


					}
				}
				catch (Exception ex)
				{
					MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
				}
			}
		}

		private void button2_Click(object sender, EventArgs e)
		{
			if (openFileDialog1.FileName != null)
				using (StreamWriter sw = new StreamWriter(openFileDialog1.FileName, true))
				{
					sw.WriteLine(tb_lastname.Text + ", " + tb_firstname.Text + ": " + tb_id.Text + " \"" + tb_class.Text + "\" \"" + tb_grade.Text + "\"");
				}
		}


	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.