I have prevented numbers from being typed in text box using key down event. But when using Ctrl+V or pasting content through mouse, the numbers are being entered in the text box. How to prevent this? I have to allow all text to be pasted/typed except numbers.
+3
A:
use the TextBox.TextChanged event. Then use the same code as you have in the KeyDown event. In fact, you no longer need the keydown event
TerrorAustralis
2010-09-21 06:52:59
I have used KeyEventArgs of key down event and using e.KeyCode, I have prevented numbers! But while using text changed event i can't get key code for a key!
banupriya
2010-09-21 07:11:38
A:
You can use the JavaScript change event (onchange) instead of the keydown event. It'll check only when the user leaves the textbox though.
KBoek
2010-09-21 06:59:16
Using Javascript events is *really* hard in winforms applications ;)
Fredrik Mörk
2010-09-21 07:00:12
+2
A:
On quite simple approach would be to check the text using the TextChanged
event. If the text is valid, store a copy of it in a string variable. If it is not valid, show a message and then restore the text from the variable:
string _latestValidText = string.Empty;
private void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox target = sender as TextBox;
if (ContainsNumber(target.Text))
{
// display alert and reset text
MessageBox.Show("The text may not contain any numbers.");
target.Text = _latestValidText;
}
else
{
_latestValidText = target.Text;
}
}
private static bool ContainsNumber(string input)
{
return Regex.IsMatch(input, @"\d+");
}
This will handle any occurrence of numbers in the text, regardless of where or how many times they may appear.
Fredrik Mörk
2010-09-21 07:11:26