Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
        }
like image 303
Wizard Avatar asked May 01 '12 17:05

Wizard


2 Answers

Here is another simple solution

try
{
    int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
    MessageBox.Show("Please provide number only");
}
like image 130
COLD TOLD Avatar answered Oct 12 '22 01:10

COLD TOLD


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.

like image 20
Somebody Avatar answered Oct 12 '22 01:10

Somebody