How can I allow input only 0 or 1 in a TextBox?

How to limit a TextBox control to a valid value of 0 and 1?

Thanks. And I have one more question: how to disable putting text from the clipboard into my text box control?

+7
c # textbox
source share
3 answers

Using the KeyPress Event

 private void NumericOnlyKeyBox_KeyPress(object sender, KeyPressEventArgs e) { var validKeys = new[] { Keys.Back, Keys.D0, Keys.D1 }; e.Handled = !validKeys.Contains((Keys)e.KeyChar); } 

Setting e.Handled to true / false indicates whether the character should be accepted in the field or not.

You can learn more about KeyPressEventArgs on MSDN.

Note

Keys.Delete should span the keys Keys.Delete, Keys.Backspace and other back buttons.

+11
source share

If you want to show numbers, not a check or something, but only want to allow 0 or 1, you can use the NumericUpDown control and set min to 0 max to 1 and step 1.

If you really need a text box, I would use Filip's answer, but I would set MaxLength from it to 1 so I don't have to worry about 00, 11 or 01 or similar values.

+2
source share

You can see the answer to this question:

C # Input check for text field: float

+1
source share

All Articles