views:

1598

answers:

5

I need to be able to lock down the valid characters in a textbox, I presently have a regex which I can check each character against such as

[A-Za-z]

would lock down to just Alpha characters.

protected override void OnKeyPress(KeyPressEventArgs e)
{
  if (e.KeyChar == (char)Keys.Back)
  {
    base.OnKeyPress(e);
    return;
  }
  if (String.IsNullOrEmpty(this._ValidCharExpression))
  {
    base.OnKeyPress(e);
  }
  else
  {
    bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success;
    if (isValidChar)
    {
      base.OnKeyPress(e);
    }
    else
    {
      e.Handled = true;
    }
  }
}

I had placed the regex code in the OnKeyPress code, but I wat to allow all special keys, such as Ctrl-V, Ctrl-C and Backspace to be allowed.

As you can see I have the backspace key being handled. However, Ctrl-V, for example cannot see the V key because it runs once for the ctrl key but does not see any modifiers keys.

What is the best way to handle this situation?

+1  A: 

Why don't you put the check for valid characters in the OnTextChanged event

and then deal with the Ctrl+C, Ctrl+V in the on key down

Also you can use the e.ModifierKeys == Keys.Control to test for control keys

http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.aspx

tdyen
+2  A: 

What if you put the validation in OnTextChanged instead of OnKeyPress, but each time it passes validation you save the value to a variable? Then you can revert if the user pastes or types an incorrect string, as well as give some other UI hint that something was invalid (e.g. set a Label's text).

Jimmy
+4  A: 

MaskedTextBox may be right for you.

You can also look at the FilterTextBox over at CodeProjct. You can use it (or the approach described) to do what you intend. The basic idea is to cancel the change before it is becoming visible (via an OnTextChanging event).

Tomalak
A: 

You can use one of the OnKeyPress / OnKeyUp / OkKeyDown events and then use the Char.IsLetter method to check that the entered key is a letter.

Rune Grimstad
A: 

The solution that I have come up with is to check the keys in the OnKeyDown event and then setting a flag if the keypress should be handled, which is then check in the OnKeyPress event.

protected override void OnKeyDown(KeyEventArgs e)
 {
    Keys keyCode = (Keys)e.KeyValue;
    base.OnKeyDown(e);
    if ((e.Modifiers == Keys.Control) ||
       (e.Modifiers == Keys.Control) ||
       (keyCode == Keys.Back) ||
       (keyCode == Keys.Delete))
    {
      this._handleKey = true;
    }
    else
    {
      // check if the key is valid and set the flag
      this._handleKey = Regex.Match(key.ToString(), this._ValidCharExpression).Success;
    }
  }




protected override void OnKeyPress(KeyPressEventArgs e)
  {
    if (this._handleKey)
    {
      base.OnKeyPress(e);
      this._handleKey = false;
    }
    else
    {
      e.Handled = true;
    }
  }
benPearce