When performing the C#program, you may encounter an error of "incorrect input string format". This usually occurs during the input and parsing process.
In the code you provided, the error occurred because the values of 'a' and 'b' are parsed when creating a window, which may be before the user input is entered in the text box. To solve this problem, please move the analysis of 'a' and 'b' to the button to click on the event, where you can determine the existence of the input value.
In addition, please consider using the 'int32.tryparse' method, which can elegantly handle the input string without containing an effective integer. This method returns a Boolean value to indicate success or failure, so that error recovery and stronger input processing allows errors.
The following is the modified version of your code, which contains these suggestions:
By updating the integer value in the button to click on the event and use the 'int32.tryparse' method. Your code will now process the input elegantly and provide a more powerful calculator application. Add an error treatment. When the input is not an integer, a message box prompts the user. At the same time, the
<code class="language-csharp">public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (int.TryParse(textBox1.Text, out int a) && int.TryParse(textBox2.Text, out int b)) { add(a, b); result(); } else { MessageBox.Show("请输入有效的整数!"); } } private void button2_Click(object sender, EventArgs e) { if (int.TryParse(textBox1.Text, out int a) && int.TryParse(textBox2.Text, out int b)) { substract(a, b); result(); } else { MessageBox.Show("请输入有效的整数!"); } } // ... (其他方法省略,以简洁起见) ... private void add(int a, int b) { /* 加法运算 */ } private void substract(int a, int b) { /* 减法运算 */ } private void result() { /* 显示结果 */ }</code>
methods are modified to accept parameters, and the code structure is corrected. add
The above is the detailed content of How to Fix 'Input String Format Error' in a C# Calculator?. For more information, please follow other related articles on the PHP Chinese website!