This was something that frustrated me for about an hour today and thought that I would share my solution.
Lanaguage: C#
Proficiency: Beginner (Understanding of events)
IDE: VS 2003
Scenario: On a Windows application you have a textbox in which you want the user to only insert digits (0-9) and also allow them to erase what they have put in the textbox (the backspace key)
Solution:
In your code behind you will need to WireUp the textbox's KeyPress event so:
Code:
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtNumericKeyCheck);
Now create your method to handle the event:
Code:
private void txtNumericKeyCheck(object sender, KeyPressEventArgs e)
{
}
Pretty cut and dry thus far so lets add the code to determine which key the user is pressing:
Code:
private void txtNumericKeyCheck(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
int i = (int)c;
}
Again this is very basic, our event args pass in the key that was pressed. The second part is personal prefereance, however, IMHO conditionals are easier to write when your dealing with numbers so we convert the Character to its corrosponding ASCII number.
Lastly we need to check if the keystroke was numeric, the backspace, or anything else:
Code:
private void txtNumericKeyCheck(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
int i = (int)c;
if((i < 48 || i > 57) && i != 8)
{
e.Handled = true;
return;
}
}
The keystroke 0 (Zero) is 48 and 9 is 57 so that becomes the first half of our condition and secondly we check for the value of 8 (backspace); if the code passes those checks the keystroke is registered inside of the textbox if the checks fail we call:
which handles the keystroke and it is not registered inside of the textbox!
Also, if you are watching the length of textbox, want to verifiy the data, etc, handle it in the textboxes textChanged event as it will fire AFTER the keypress event.
Lastly this isn't, by far, the only way to achieve the end result. You could, for example, add a reference to Microsoft.VisualBasic and use the IsNumeric() function that is contained within it, place it inside a method that handles your textChanged event and if the function returns false, you know that non-numeric data is present. (I have had so so results with IsNumeric() in that data i thought would return false returned true and vice versa)
All and all pretty simple.
================================================== =========
I will only tell you how to do it, not do it for you.
Unless, of course, you want to hire me to do work for you.
================================================== =========
Read this if you want to know how to get a correct reply for your question:
http://www.catb.org/~esr/faqs/smart-questions.html
^^Took that from planoie's profile^^
^^Modified text taken from gbianchi profile^^
================================================== =========