Checking numeric input for textbox in C#

In this article show how to check whether TextBox contain numeric or not in C# whenever you input value to TextBox on event keypress and leave. This example, I am trying to check on three TextBox to make sure that they contain only numeric value. 
Figure 1: Sample Form
I’m going to check  on three TextBox : Customer  ID, Quantity, and Price. Go to the form and select on the three Textbox, and then go to Properties -->click on Events --> double click on KeyPress and Leave. See picture below:
Create event on KeyPress and Leave for textboxs
Figure 2: Create event on KeyPress and Leave for textboxs
Code :
private void TxtCustomer_KeyPress(object sender, KeyPressEventArgs e)
{
  TextBox txt = (TextBox)sender;
  if (!(e.KeyChar >= 48 && e.KeyChar <= 57) && !(e.KeyChar == 8))
  {
     //Do what you want do if input value is not numeric
     MessageBox.Show("please input numeric only !");
     txt.Focus(); 
  }
}
private void TxtCustomer_Leave(object sender, EventArgs e)
{
   bool digi = false;
   TextBox txt = (TextBox)sender;
   string number = txt.Text.Trim();
   for (int i = 0; i < number.Length; i++)
   {
     if (!char.IsNumber(number[i]))
     {
       digi = true;
     }
   }
   if (digi)
   {
      //Do what you want do if input value is not numeric
      MessageBox.Show("please input numeric only !");
      txt.Focus();
   }
        }


 Done....Now you will the result as picture below when you input value which is not numeric.

Checking numeric input for textbox in C# Checking numeric input for textbox in C# Reviewed by BeiLover on 4:23 PM Rating: 5

3 comments:

Powered by Blogger.