user2705420
user2705420

Reputation: 23

How to prevent crashing from a invalid input in C#

I made a simple application to add 2 numbers together but when I add two letters together or a invalid sign it crashes the program. How do I create a message box showing something saying "please put in a number" when someone inserts a letter

Here's my code:

public partial class frmAdd : Form
{
    string first;
    string second;
    public frmAdd()
    {
        InitializeComponent();
    }

    private void btnFirst_Click(object sender, EventArgs e)
    {
        first = txtNumber.Text;
    }

    private void btnSecond_Click(object sender, EventArgs e)
    {
        second = txtNumber.Text;
    }

    private void btnResult_Click(object sender, EventArgs e)
    {
        int a = Convert.ToInt32(first);
        int b = Convert.ToInt32(second);
        int c = a + b;
        txtResult.Text = c.ToString();
    }
}

Upvotes: 2

Views: 3119

Answers (4)

p.s.w.g
p.s.w.g

Reputation: 149040

Use TryParse instead:

private void btnResult_Click(object sender, EventArgs e)
{
    int a, b;
    if (int.TryParse(first, out a) && int.TryParse(second, out b))
    {
        int c = a + b;
        txtResult.Text = c.ToString();
    } 
    else
    {
        MessageBox.Show("Invalid Input!");
    }
}

Or perhaps a better method would be to trap the error when the user first inputs the data:

public partial class frmAdd : Form 
{ 
    int first;   // changed to int
    int second;

    private void btnFirst_Click(object sender, EventArgs e)
    {
        if (!int.TryParse(txtNumber.Text, out this.first))
        {
            MessageBox.Show("Invalid Input!");
        }
    }

    private void btnSecond_Click(object sender, EventArgs e)
    {
        if (!int.TryParse(txtNumber.Text, out this.second))
        {
            MessageBox.Show("Invalid Input!");
        }
    }

    private void btnResult_Click(object sender, EventArgs e)
    {
        int c = first + second;
        txtResult.Text = c.ToString();
    }
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

You can use NumericUpDown control instead of TextBox - it will not allow user to input invalid data.

Or you can add validation to TextBox value after user entered something. Add ErrorProvider to your form. And subscribe to Validating event of txtNumber textbox. This event will occur when textbox loses focus. If entered text is not an integer, then error will be shown near texbox, and your button will not be clicked:

private void txtNumber_Validating(object sender, CancelEventArgs e)
{
    int value;
    if (!Int32.TryParse(txtNumber.Text, out value))
    {
        errorProvider1.SetError(txtNumber, "Value is not an integer");
        return;
    }

    errorProvider1.SetError(txtNumber, "");
    first = value; // it's better to save integer value than text
}

Validation looks like:

enter image description here

Upvotes: 2

Pim Verlangen
Pim Verlangen

Reputation: 387

Instead of using Convert.ToInt32(string), you might actually use Int32.tryParse(String, out int), as shown below:

int a, b;

a = Int32.tryParse(first, out a);
b = Int32.tryParse(second, out b);

If the conversion fails, the tryParse method will result in a zero. If it succeeds, it will give you the number which is to be found in the string.

Hope it helped you out, had to find this too in my first few days of C#.

Upvotes: 0

sa_ddam213
sa_ddam213

Reputation: 43616

You can add a bit of validation to check if you can create an int from the string value passed in. int.TryParse is a simple way of doing this.

And for the MessageBox you can just use the MessageBox calss

Example:

private void btnResult_Click(object sender, EventArgs e)
{

    int a = 0;
    int b = 0;
    if (!int.TryParse(first, out a))
    {
        MessageBox.Show("first is not a number");
        return;
    }
    if (!int.TryParse(second, out b))
    {
        MessageBox.Show("second is not a number");
        return;
    }
    int c = a + b;
    txtResult.Text = c.ToString();
}

Upvotes: 0

Related Questions