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");
}
Here is another simple solution
try
{
int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
MessageBox.Show("Please provide number only");
}
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:
private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar)) e.Handled = true; //Just Digits
if (e.KeyChar == (char)8) e.Handled = false; //Allow Backspace
if (e.KeyChar == (char)13) btnSearch_Click(sender, e); //Allow Enter
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With