|
-
September 11th, 2002, 03:31 PM
#1
TextBox - Valid
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!
-
September 12th, 2002, 12:48 PM
#2
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:
Code:
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.
-
September 12th, 2002, 02:36 PM
#3
The above method can only be used for System.Windows.Forms TextBox not for a webform textbox.
-
September 12th, 2002, 02:41 PM
#4
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.
-
September 14th, 2002, 11:20 AM
#5
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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|