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);
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: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
returnstatement) following an unsuccessful conversion.