01.Blogs :
travisowens  

Setting a WinForms textbox to numbers only

I needed to create a TextBox control on my Window Form so that the user can only enter numbers.  VBers have it easier as they have a built in method to check isnumeric() but C# and other languages need to write their own.  The most popular one (but slowest) I found floating around the net was

public static bool IsNumeric(string inputData)
{
  try
  {
    int.Parse(inputData);
    return true;
  }
  catch
  {
    return false;
  }
}














And now that we have a boolean check to see if something is numeric, we can now construct an event on our textbox to see if a non number is entered.  Up in your code (it will be in [+] // Required for Windows Form Designer support) you will need to define the event of KeyPress to make checks on your control while keys are pressed via this code.

this.textbox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textbox1_KeyPress);




And now finally in your code you must create the method that you are calling to perform the check and respond accordingly

private void textbox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
  if (IsNumeric(textbox1.Text))
  {
    e.Handled = true;
  }
}









And if you want to be annoying, you could play a sound there or use the Windows default error sound.  Personally, I'm not a fan of harrasing users via audio or popups.

posted on Friday, January 30, 2004 7:42 PM by travisowens


 
03.UPDATE CALENDAR :
<January 2004>
SunMonTueWedThuFriSat
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

05.MY LINKS :

07.Subscriptions :

Subscriptions


© Copyright 2005 Microsoft Corporation. All Rights Reserved.
Terms of Use | Privacy Statement | Code of Conduct | Hosted by MaximumASP for Microsoft
WHO-BAR