I am new to C#. I'm trying to make a calculator, but the following error occurred:
Input string was not in a correct format.
This is the summary of the code:
double num1, num2, result;
private void button14_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(textBox1.Text);
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text); **//ERROR OCCURED HERE**
result = num1 - num2;
}
private void button13_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(textBox1.Text);
textBox1.Text = String.Empty;
num2 = System.Double.Parse(textBox1.Text); **//ERROR OCCURED HERE**
result = num1 + num2;
}
How to convert string to a double type?
Also remember that the Parse method is relying on the culture of your operating system to perform the conversion, so try to change your code to
num2 = double.Parse(textBox1.Text, CultureInfo.InvariantCulture);
You might also consider to use the
double.TryParse
method for better exception handling.
What are you trying to achieve with this code? It seems that your algorythm is wrong.
Like others said, this code
textBox1.Text = String.Empty;
num2 = double.Parse(textBox1.Text);
will throw an Exception because an empty string cannot be converted to Double!
So, I'm wondering why did you reset your field. I thought about it for a while, and maybe I got what are you trying to do. Let's say you type a number in TextBox1. Then you press the "-" button to subtract and then you want to enter the second number to view the result. Is this the case? If it is, the code you wrote is not going to wait for your next input!
In fact, when you click the button, it just executes all the lines you wrote. I'd write something like this instead.
double num1, num2, result;
string operation;
private void button14_Click(object sender, EventArgs e) //Minus Button
{
if (textBox1.Text != String.Empty) //Added if statement to see if the textBox is empty
num1 = Convert.ToDouble(textBox1.Text);
else
num1 = 0; //If textBox is empty, set num1 to 0
textBox1.Text = String.Empty;
operation = "-";
}
private void button13_Click(object sender, EventArgs e) //Equals Button
{
if (textBox1.Text != String.Empty)
num2 = Convert.ToDouble(textBox1.Text);
else
num2 = 0;
if (operation == "-")
{
result = num1 - num2;
textBox1.Text = Convert.ToString(result);
}
if (operation == "+")
{
//You got it
}
//And so on...
}
EDIT: If the string is empty, this is going to always throw Exceptions, so I added a control. If the string is empty, value becomes zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With