c# - command line for a text to appear if number1 and/or number2 are empty

89 views Asked by At

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";
    }
}
1

There are 1 answers

0
Nino On

Application would throw exception in one of these two lines if any of them is empty:

Zahl1 = Convert.ToDouble(textBox1.Text); 
Zahl2 = Convert.ToDouble(textBox2.Text); 

You should check if TextBoxes are empty before converting their value to decimal. So, try like this:

private void button1_Click(object sender, EventArgs e)
{
    if (String.IsNullOrEmpty(textBox1.Text) || String.IsNullOrEmpty(textBox2.Text))
    {
        label2.Text = "Bitte 2 Zahlen eingeben";
    }
    else
    {
        Zahl1 = Convert.ToDouble(textBox1.Text); 
        Zahl2 = Convert.ToDouble(textBox2.Text); 
        label2.Text = label2.Text.Replace(".", ",");

    }
}

additionally, you should check if that text could be converted to double. What if user writes abc in textBox1 and 3 in textBox2? You'll get an exception.

So, add additional checking, like this:

double z1;
double z2;
if (String.IsNullOrEmpty(textBox1.Text) || String.IsNullOrEmpty(textBox2.Text))
{
    label2.Text = "Bitte 2 Zahlen eingeben";
}
else if (!double.TryParse(textBox1.Text, out z1) || !double.TryParse(textBox2.Text, out z2))
{
    label2.Text = "Das sind keine korekt Zahlen! :)";
}
else
{
    //rest of your code
    Zahl1 = Convert.ToDouble(textBox1.Text); 
    //etc....
}