tags:

views:

193

answers:

3

How can I limit the TextBox control to only allow the values 0 and 1?

Thanks. And I have one more question: How can I disable put text from clipboard in my textbox control?

+1  A: 

You may want to see the answer to this related question:

C# Input validation for a Textbox: float

Arnaud Leymet
+10  A: 

By using the event KeyPress

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 if the character should be accepted to the box or not.

You can read more about KeyPressEventArgs on MSDN.

Note

Keys.Delete should cover Keys.Delete, Keys.Backspace and other "Back" buttons.

Filip Ekberg
Better this: `e.Handled = (e.KeyChar == Keys.D0) || (e.KeyChar == Keys.D1);`
abatishchev
+1 -- Thanks. I didn't know that. :-)
Pretzel
@abatishchev -- haha, clever. :-D
Pretzel
@abatischev, Don't forget the numpad. :)
Filip Ekberg
thank you for you answer!
Alexry
You should also take care of backspace and delete
PoweRoy
@PoweRoy, true, you need to accept those keys aswell.
Filip Ekberg
Almost downvoted for using if-statement to set a boolean.
SergioL
arrow keys? tab? what if they want to paste using Ctrl+V?
adam0101
@adam0101: Try before ask ;) `KeyPress` will not be fired on pressing delete, arrows or tab. Yes, Ctrl+C/Ctrl+V will bot work but Cntrl+Ins/Shift+Ins will.
abatishchev
@adam0101, refactored a bit. You can now use Delete key, Backspace, 0 , 1 numpad 0 and 1.
Filip Ekberg
Right-click the text box and select Paste.
Hans Passant
@Hans, Actually one solution would be to use `protected override void WndProc(ref Message m)` and check for paste/copy messages. But then you would have to override the TextBox and do that. Another solution is to override the TextChanged event and just add a loop that checks each character and removes the incorrect ones. To make the example a bit simple, I wont add that though, there's enough information in this last comment. :)
Filip Ekberg
+2  A: 

If you do want to show the numbers rather than a check or something but only want to allow 0 or 1 you could use a NumericUpDown control and set min to 0 max to 1 and step to 1.

If you do actually need a textbox I'd use Filip's answer but I'd set the MaxLength of it to 1 to avoid having to worry about 00, 11 or 01 or similar values.

ho1
+1 -- I personally think that this is the best answer, really. And if you want it as a string, well then use .ToString() -- And you're done. (and so little code, too!)
Pretzel