C
C#10mo ago
RXPHXEL

I am stuck with variables

private void button1_Click(object sender, EventArgs e) { char op; int first, second, result;
first = Convert.ToInt32(textBox1.Text); second = Convert.ToInt32(textBox2.Text); result = Convert.ToInt32(textBox4.Text); op = Convert.ToChar(textBox3.Text); switch (op) { case '+': result = first + second; break; case '-': result = first - second; break; case '*': result = first * second; break; case '/': result = first / second; break; default: textBox3.Text = "Invalid Operator!"; break; } } I am trying to build a calculator with using the switches, my goal to take the user input from textbox 1 and 2 and by using the switches calculate the result. However, whenever I start the program it says "The input string was not correct" for the result line. I tried to convert it to int and double but it didn't work and I am simply stuck, how can I solve it?
4 Replies
Angius
Angius10mo ago
Probably because textBox4.Text is empty An empty string is not a number So Convert throws an exception From what I see, textBox4 is where the result should go, it has no initial value, so there's no need to even try to convert it to a number @RXPHXEL
RXPHXEL
RXPHXELOP10mo ago
Yep textbox 4 is empty How can I rewrite the code then
Angius
Angius10mo ago
Don't get the result Make the result an empty int variable, for example And only at the end, after the switch, assign its value to textBox4.Text textBox4.Text = $"The result is {result}"; for example
RXPHXEL
RXPHXELOP10mo ago
Thank you so much
Want results from more Discord servers?
Add your server