Restrict numbers and letters in textbox - C#

前端 未结 6 1551
心在旅途
心在旅途 2021-01-24 10:35

I want to restrict what numbers and letters can be entered into a textbox. Let\'s say I only want to allow numbers 0-5 and letters a-d (both lower and uppercase). I already tri

6条回答
  •  一向
    一向 (楼主)
    2021-01-24 10:59

    Override the PreviewKeyDownEvent like this:

        private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.A || e.KeyCode == Keys.B || ...)
                e.IsInputKey = true;
            else
                e.IsInputKey = false;
        }
    

    This will tell the textBox which keys it will consider as a user input or not.

提交回复
热议问题