How can I allow only 0 or 1 to be entered in a Tex

2019-02-17 04:17发布

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?

标签: c# textbox
3条回答
在下西门庆
2楼-- · 2019-02-17 05:11

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.

查看更多
The star\"
3楼-- · 2019-02-17 05:12

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.

查看更多
干净又极端
4楼-- · 2019-02-17 05:20

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

C# Input validation for a Textbox: float

查看更多
登录 后发表回答