Click to See Complete Forum and Search --> : TextBox - Valid
GNilsson
September 11th, 2002, 03:31 PM
I'm doing a calculation program and I only want numbers to be typed in the TextBox.
How do I make a validation so letters and other characters can't be typed.
I thought this was simple but I canīt find the key.
Thank you for the attention!
CPCericola
September 12th, 2002, 12:48 PM
You will want to consume the TextBox.KeyPress event. You then check the value of the KeyPressEventArgs.KeyChar. If it's not within your range, you set e.handled = true.
Here's a code snipped to better explain it:
void keypressed(Object o, KeyPressEventArgs e)
{
if(e.KeyChar < 'a' || e.KeyChar > 'z')
{
e.Handled = true; // prevent from passing back to Windows for handling.
}
}
HTH.
Gjain
September 12th, 2002, 02:36 PM
The above method can only be used for System.Windows.Forms TextBox not for a webform textbox.
Gjain
September 12th, 2002, 02:41 PM
Add this code to InitializeComponent() function:
this.TextBox.KeyPress += new
System.Windows.Forms.KeyPressEventHandler(this.TextBox_KeyPress);
and this to the code:
private void TextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((e.KeyChar!=(char)8)&&(e.KeyChar!=(char)32)&&(!Char.IsDigit(e.KeyChar)) )
//the ASCII character code for SAPCE is 32 and BACKSAPCE is 8
{
e.Handled=true;
}
}
the above fn will allow only digits, space and backspace to be typed in the textbox.
Hope this helps.
GNilsson
September 14th, 2002, 11:20 AM
Thank you for your help!!
Itīs working fine. The program is a windows application but the goal is to make it a web application. As Iīm a beginner at C#, I have to start somewhere.
:)
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.