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!
Printable View
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!
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:
HTH.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.
}
}
The above method can only be used for System.Windows.Forms TextBox not for a webform textbox.
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.
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.
:)