简体   繁体   中英

Converting Textbox to Integer, Taking String from Array

I'm trying to convert the user input from a textbox to an integer (in c#), and then output a value from an array with the index of that integer. Here's a small part of my code:

 public Form1()
{
 InitializeComponent();
        string[] Cmaj = new string [7];
            Cmaj[1] = "C";
            Cmaj[2] = "D";
            Cmaj[3] = "E";
            Cmaj[4] = "F";
            Cmaj[5] = "G";
            Cmaj[6] = "A";
            Cmaj[7] = "B";


       int roman = int.Parse(textBox3.Text);
       textBox4.Text = Cmaj[roman];

}

But each time I run this, I get an error about "int roman = int.Parse(textBox3.Text);" (Listed below). I originally had Convert.ToInt32 instead of int.Parse, but I saw another question about this topic that said to use parse rather than convert. This, however, didn't change much. What should I do?

Error: An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

Thanks.

You are in the constructor of your component. So the text is probably empty and cause an exception.

Probably you want to add the parsing logic on an event like text changed or button clicked.

So from the form builder add the event handler, than move the logic into that method.

To better understand when each metdod il called I suggest you to add a break point on the first { of each method, and you can follow the event flow.

Is a good idea to manage error: you can wrap with a try...catch or use int.TryParse that requires an out variable.

使用不同的方式

  1. Convert.ToInt32(string);
  2. int val = 0; Int32.TryParse(string, out val );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM