This error occurred when trying to convert the string into an integer, but the string does not contain an effective integer representation form. In this example, the error may be caused by the following lines:
When the window is first created, the text box Textbox1 and TextBox2 will be empty, so the Int32.PARSE method will fail.
a = Int32.Parse(textBox1.Text); b = Int32.Parse(textBox2.Text);
<决> Solution:
In order to solve this error, you can move the integer parsing to the button to click the event processing program, where you can use a user input. In addition, you can use the Int32.TryParse method. If the string is not an integer representation form, this method can return false, so you can handle errors elegantly.
The code of this improvement first checks whether
andprivate void button1_Click(object sender, EventArgs e) { if (Int32.TryParse(textBox1.Text, out int a) && Int32.TryParse(textBox2.Text, out int b)) { add(); result(); } else { // 处理错误,例如显示错误消息 MessageBox.Show("请输入有效的整数。"); } }
functions; otherwise, it will display a message box to inform the user that the input is invalid. This avoids the collapse of the program and provides a better user experience. Please note that we now use and textBox1.Text
to declare and initialize textBox2.Text
and add()
variables. This is the improvement syntax introduced by C# 7 and higher versions. result()
The above is the detailed content of How to Handle 'Input string was not in a correct format' Errors When Parsing Integers from TextBoxes?. For more information, please follow other related articles on the PHP Chinese website!