0

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;
}
petya1969
  • 49
  • 4

5 Answers5

1
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);
CSDev
  • 3,177
  • 6
  • 19
  • 37
1

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

fahime
  • 179
  • 2
  • 12
1

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.

TimB
  • 970
  • 8
  • 17
1

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;

    }
0

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?

Toby Smith
  • 1,505
  • 2
  • 15
  • 24
  • 1
    This is a bad practice – Roberto Pegoraro May 14 '19 at 17:29
  • @Roberto - so is calling something out for being bad practice without saying _why_ it is bad practice. It all seems a little moot though when any answer which actually answers the question will be bad practice - a TextBox is inappropriate for a boolean input from the user. A Checkbox or Radiobuttons sure - _maybe_ a NumericUpDown but even that isn't really appropriate. – Toby Smith May 14 '19 at 21:47