Reputation: 11
private void txtLastName_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (!char.IsDigit((char)e.Key)) e.Handled = true;
}
But It not support all key in keyboard .
Upvotes: 1
Views: 6346
Reputation: 57
This thread is really old, but if someone still needs it, here is code that is working for me
(Edited a little bit Usman's code)
private void TextValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^a-zA-Z]+");
e.Handled = regex.IsMatch(e.Text);
}
And don't forget to put code below to TextBox that you want to accept only text ( in xaml )
PreviewTextInput="TextValidationTextBox"
Upvotes: 0
Reputation: 818
private void txtLastName_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.Text, "^[a-zA-Z]"))
{
e.Handled = true;
}
}
Upvotes: 5
Reputation: 26635
You must use IsLetter
.
private void txtLastName_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (Char.IsLetter((char)e.Key)) e.Handled = true;
}
Upvotes: 1