C#calculator "Incorrect input string format" error solution
In C#, trying to analyze the invalid string to numerical data type may cause the "input string format to incorrect" error. This error occurs when the string passed to the method does not meet the expected format of the target data type.
In a given C#calculator code, the error occurred because the Parse
method is used in the constructor to convert the empty string (retrieved from the text box) to an integer. By default, the text box is empty when creating a window.
Solution: Parse
In order to solve this problem, the code should update the values of and in the button click on the event, rather than in the constructor, because the text box contains meaningful values in the button click event. In addition, the method should be used to process the string may not contain an effective integer.
It will not throw an exception to make it easier to deal with.
a
The following is the modified code fragment: b
TryParse
TryParse
This modification will change and
and
, which is more in line with the code style of modern C#, and clearly specifies the type of output parameters. More importantly, it adds a placeholder<code class="language-csharp">// ... (不变的代码) public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (Int32.TryParse(textBox1.Text, out int a)) { // 执行加法运算 } else { // 处理无效输入,例如显示错误消息 } if (Int32.TryParse(textBox2.Text, out int b)) { // 执行加法运算 } else { // 处理无效输入,例如显示错误消息 } add(); result(); } // ... (其余代码不变)</code>
The above is the detailed content of How to Fix the 'Input String Was Not in a Correct Format' Error in a C# Calculator?. For more information, please follow other related articles on the PHP Chinese website!