tags:

views:

44

answers:

2

I want to validate the input of a TextBox to be a binary number.

I know I can do this with RegEx but I wanted a more 'inmediate' validation, like allowing just 1's and 0's to be entered.

I thought of using MaskedTextBox but I don't know how to just allow those two characters.

+1  A: 

There's no way of getting it out of the box with MaskedTextBox.

This answer shows you a way of achieving this (just adapt the code to parse only 0s and 1s):

How to make the MaskedTextBox only accept HEX value?

Leniel Macaferi
+2  A: 

Implement the KeyPress event. Set e.Handled = true if you don't like the key:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
        // Allow backspace, 0 and 1
        e.Handled = !("\b01".Contains(e.KeyChar));
    }
Hans Passant
+1 I don't like `MaskedTextBox`, where users can't copy-paste. Btw why not just `e.Handle = !("01".Contains(e.KeyChar) || e.KeyChar == 8)`.
Danny Chen
Very simple answer, thank you.
vash47