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

后端 未结 3 1308
鱼传尺愫
鱼传尺愫 2021-01-12 08:56

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 c

3条回答
  •  隐瞒了意图╮
    2021-01-12 09:32

    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.

提交回复
热议问题