Reputation: 49
How can you make it so that only the numbers 1 or 2 can be entered into the textbox? And you can also use the Backspace key. The maximum length of textbox characters is one. I know how to enter only numbers:
char number = e.KeyChar;
if (!Char.IsDigit(number) && number != 8)
{
e.Handled = true;
}
Upvotes: 0
Views: 249
Reputation: 92
Use SuppressKeyPress property
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
/*
* 8: backspace
* 49: 1
* 50: 2
*/
int[] validKeys = {8, 49, 50};
if (!validKeys.Contains(e.KeyValue))
e.SuppressKeyPress = true;
}
Upvotes: 1
Reputation: 1000
I'd use the NumericUpDown control instead of a TextBox. There you can set min to 1, max to 2, and your user can enter numbers or use the arrow keys to increase/decrease.
If you MUST use a TextBox, then set it MaxLength property to 1, and add a KeyDown event and handler. In the handler you can do:
if(!(e.KeyCode == Keys.D1 || e.KeyCode == Keys.D2 || E.KeyCode == Keys.Delete))
{
// Of course, you can add even more keys up there. For example, you might add Keys.Numpad1 etc...
e.handled = true;
}
So, for the TextBox you already did the right thing, basically.
Upvotes: 1
Reputation: 3235
char number = e.KeyChar;
if (number != '1' && number != '2' && number != '\b')
{
e.Handled = true;
}
or just
e.Handled = e.KeyChar != '1' && e.KeyChar != '2' && e.KeyChar != '\b';
or for more expressiveness
private static readonly char[] allowedChars = { '1', '2', '\b' };
// ...
e.Handled = !allowedChars.Contains(e.KeyChar);
Upvotes: 1
Reputation: 179
All you need is use RegularExpressions and you can check any input with expressions.
I think you should visit this question: Only allow specific characters in textbox
Upvotes: 1
Reputation: 1605
I assume all you need is something like the following in the textbox's TextChanged event?
if (textbox.text != "1" && textbox.text != "2")
{
textbox.text = string.empty;
}
I'm not sure what the number != 8
is for in your question?
Upvotes: 0