Lion Lion - 10 months ago 54
C# Question

Validating a Textbox field for only numeric input.

I have created a form-based program that needs some input validation. I need to make sure the user can only enter numeric values within the distance Textbox.

So far, I've checked that the Textbox has something in it, but if it has a value then it should proceed to validate that the entered value is numeric:

else if (txtEvDistance.Text.Length == 0)
MessageBox.Show("Please enter the distance");
else if (cboAddEvent.Text //is numeric)
MessageBox.Show("Please enter a valid numeric distance");

Answer Source

You may try the TryParse method which allows you to parse a string into an integer and return a boolean result indicating the success or failure of the operation.

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
    // it's a valid integer => you could use the distance variable here