3D-kreativ
3D-kreativ

Reputation: 9299

How to avoid error if textbox is empty?

I'm looking for a solution to avoid an error if one or both of the textboxes are empty? I have tested to check if the value of height and width is null, but that I can only do after the code, and then it's to late!? Help is preciated! Thanks!

// Get values from text boxes
int height = Convert.ToInt32(txtInputA.Text);
int width = Convert.ToInt32(txtInputB.Text);

Upvotes: 0

Views: 2945

Answers (3)

Writwick
Writwick

Reputation: 2163

Here is how you can check if the TextBox is not Empty :

int height;
int width;
if (!string.IsNullOrWhiteSpace(txtInputA.Text) & !string.IsNullOrWhiteSpace(txtInputB.Text))
{
    // Get values from text boxes
    height = Convert.ToInt32(txtInputA.Text);
    width = Convert.ToInt32(txtInputB.Text);
}
else
{
    MessageBox.Show("Please Enter Height and Width!");
}

Upvotes: -1

Douglas
Douglas

Reputation: 54877

Since you’re trying to parse the user input as integer, you need to check for more than just empty strings. What if the input contains non-numeric characters? What if the number is too large?

The easiest way to validate all this would be through Int32.TryParse, which checks validity and performs the conversion (if valid) in a single call:

int height, width;
if (int.TryParse(txtInputA.Text, out height) == false)
    // Alert: invalid height.
if (int.TryParse(txtInputB.Text, out width) == false)
    // Alert: invalid width.

Edit: By the commented “Alert”, I’m assuming that you will throw some exception that will then be caught (by a calling method) and displayed to the user. If you’re going to display the error message directly from the above logic, then make sure to stop executing the method (e.g. through a return statement) following an unsuccessful conversion.

Upvotes: 4

Tigran
Tigran

Reputation: 62248

You can do it like this:

  string aText = string.IsNullOrEmpty(txtInputA.Text)?"0":txtInputA.Text;
  int height = Convert.ToInt32(aText);

or you can do it like:

  int height = 0;
  int.TryParse(txtInputA.Text, out height);

Upvotes: 1

Related Questions