F. Pajic
F. Pajic

Reputation: 41

App crashes when nothing is entered in the TextBoxes I'm trying to parse

I'm developing an app for windows phone in Visual Studio and it's my first time using C# language in general because I'm an Android developer and I can't figure out why my app crashes on button press if nothing is entered.

If someone could help that would be awesome. Thanks alot!!

private void sum_Click(object sender, RoutedEventArgs e)
{
    decimal n1 = decimal.Parse(num1.Text);
    decimal n2 = decimal.Parse(num2.Text);
    decimal n3 = decimal.Parse(num3.Text);

    if (n1.Equals(null) || n2.Equals(null) || n3.Equals(null))
    {
        sum1.Text = "Enter something!";
    }
    else
    {
        decimal sum = n1 + n2 + n3;
        String m = Convert.ToString(sum);
        sum1.Text = m;
    }
}

Upvotes: 1

Views: 178

Answers (1)

Grant Winney
Grant Winney

Reputation: 66511

Attempting to parse empty text fields (or fields with invalid data) is the most likely candidate for throwing an exception and causing a crash. Also, the result of decimal.Parse is not going to be null, so the if portion of your if/else block won't execute.

I'd recommend using decimal.TryParse instead, which allows you to do something (like display your message) when parsing fails.

private void sum_Click(object sender, RoutedEventArgs e)
{
    decimal n1;
    decimal n2;
    decimal n3;

    if (decimal.TryParse(num1.Text, out n1)
        && decimal.TryParse(num2.Text, out n2)
        && decimal.TryParse(num3.Text, out n3))
    {
        decimal sum = n1 + n2 + n3;
        String m = Convert.ToString(sum);
        sum1.Text = m;
    }
    else
    {
        sum1.Text = "One or more fields has a missing/invalid value.";
    }
}

Upvotes: 6

Related Questions