Reputation: 784
I have text box in c# windows form. Here I'm limiting the input of the tsextbox only to numeric values.
private void txtpref02_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar)))
e.Handled = true;
}
I have two other requirements.
Upvotes: 1
Views: 755
Reputation: 35260
Here is how I'd do it:
private void txtpref02_KeyDown(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Keys.D0:
case Keys.NumPad0:
case Keys.D1:
case Keys.NumPad1:
case Keys.D2:
case Keys.NumPad2:
case Keys.D3:
case Keys.NumPad3:
case Keys.Back:
case Keys.Delete:
return;
default:
e.SuppressKeyPress = true;
e.Handled = true;
break;
}
}
Also, you can set the MaxLength
property to 1
to limit the number of characters as you've indicated.
Please note: this code is using the KeyDown
event, not the KeyPress
event.
Upvotes: 3
Reputation: 5259
Try this:
private void txtpref02_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsDigit(e.KeyChar)) || e.KeyChar == (char)8)
e.Handled = true;
}
To accept only one character, you can use the MaxLength
property of the TextBox
.
Upvotes: 0