I'm trying to program a simple calculator for a school task, but I'm having the issue that the calculator always crashes if I leave textBox1 & textBox2 empty. Instead I want a text to appear in label2 if one of them or both are left empty:
private void button1_Click(object sender, EventArgs e)
{
Zahl1 = Convert.ToDouble(textBox1.Text);
Zahl2 = Convert.ToDouble(textBox2.Text);
label2.Text = label2.Text.Replace(".", ",");
if (String.IsNullOrEmpty(textBox1.Text) | String.IsNullOrEmpty(textBox2.Text))
{
label2.Text = "Bitte 2 Zahlen eingeben";
}
}
Application would throw exception in one of these two lines if any of them is empty:
You should check if TextBoxes are empty before converting their value to
decimal
. So, try like this:additionally, you should check if that text could be converted to double. What if user writes abc in
textBox1
and 3 intextBox2
? You'll get an exception.So, add additional checking, like this: