Search code examples
c#winformstextbox

WinForms Textbox only allow numbers between 1 and 6


I want to restrict my WinForms Textbox so it only allows numbers between 1 and 6 to be entered. No letters, no other symbols or special characters, just those numbers.

How do I do that?


Solution

  • Have you tried SupressKeyPress?

    if (e.KeyCode < Keys.D1 || e.KeyCode > Keys.D6 || e.Shift || e.Alt)
            {
                e.SuppressKeyPress = true;
            }
    
            if (e.KeyCode == Keys.Back)
            {
                e.SuppressKeyPress = false;
            }
    

    The 2nd If makes you able to press backspace if you want to change what you wrote.