1

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 tried using a masked text box but it only let me specify numbers only, letters only (both without restriction) or numbers and letters together but in a particular order. Best scenario would be: user tries to enter number 6 and nothing gets entered into the textbox, same for letters outside the range a-f. I think the best event to use would be the Keypress event, but I am at a loss as to how I can achieve the restriction thing.

Peter Kelly
  • 14,253
  • 6
  • 54
  • 63
gacanepa
  • 323
  • 4
  • 16

6 Answers6

5

Use the KeyPress Event for your textbox.

protected void myTextBox_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs)
{
    e.Handled = !IsValidCharacter(e.KeyChar);
}

private bool IsValidCharacter(char c)
{
    bool isValid = true;

    // put your logic here to define which characters are valid
    return isValid;
}
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
1
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;

// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if(e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
    //If shift key was pressed, it's not a number.
    if (Control.ModifierKeys == Keys.Shift) {
        nonNumberEntered = true;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for the flag being set in the KeyDown event.
    if (nonNumberEntered == true)
    {
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;
    }
}
MANISHDAN LANGA
  • 2,227
  • 6
  • 29
  • 43
  • This worked like a charm! I only had to add the restriction for the letters. Now that I think of it, what would be the best way to do the same thing if I have, let's say, 3 textboxes in the same form and I want to check all of them? I was thinking of putting everything into a method but then I realized that there are events that belong to a particular control. I could copy the same code for every textbox but it would be a lot of code! What would you do? – gacanepa Mar 07 '12 at 13:58
1

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.

edeboursetty
  • 5,669
  • 2
  • 40
  • 67
0

Use the KeyDown event and if the e.Key is not in your allowable set, then just e.Handled = true.

An alternative would be accept all input, validate it and then provide useful feedback to the user, for example an error label asking them to enter data within a certain range. I prefer this method as the user knows something went wrong and can fix it. It is used throughout the web on web forms and would be not at all surprising for a user of your app. Pressing a key and getting no response at all might be confusing!

http://en.wikipedia.org/wiki/Principle_of_least_astonishment

Peter Kelly
  • 14,253
  • 6
  • 54
  • 63
0

The Keypress event is probably your best bet. Do a check there if the entered char is not the char you want, set e.SuppressKey to true to make sure the KeyPress event is not fired, and the char is not added to the textbox.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
0

If you are using ASP.NET Web Forms a regular expression validation would be the easiest. In MVC, a jQuery library such as MaskedEdit would be a good place to start. The answers above document the Windows forms approach well.

Darren
  • 68,902
  • 24
  • 138
  • 144
neuhoffm
  • 33
  • 1
  • 7