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");
}
I agree with Int.TryParse but as an alternative you could use Regex.
Here is another simple solution
You can do it by javascript on client side or using some regex validator on the textbox.
Javascript
Textbox (with fixed ValidationExpression)
If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:
This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.
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.
I have this extension which is kind of multi-purpose:
It works for other data types. Should work fine for what you want to do.