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.