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?
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.