Reputation: 83
hi i want to set my text box only with the alphabets i have tried the following code, it's working fine for the keyboard keys.but if i press the numpad key numbers it is accepting numbers can anyone please help me, much appreciated thanks.
bool isvalid = true;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyValue <65 || e.KeyValue > 90) && (e.KeyValue<97||e.KeyValue>122) e.KeyValue != 8))
{
isvalid = false;
MessageBox.Show("only alphabets");
}
else
{
isvalid = true;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (isvalid == false)
{
e.Handled = true;
}
else
{
e.Handled = false;
}
}
Upvotes: 2
Views: 164
Reputation: 2590
In the KeyDown event what you will get on e.KeyValue is code of key on keyboard not characters, See Keys Enumeration. This condition is true for A-Z and a-z.
(e.KeyValue >= Keys.A && e.KeyValue <= Keys.Z)
Upvotes: 1
Reputation: 9064
Use Regex.IsMatch
property.
Can Use Following Code:
private void txtAlphaOnly_TextChanged(object sender, EventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch("^[a-zA-Z]", txtAlphaOnly.Text))
{
MessageBox.Show("Alphabets Only Allowed");
}
}
MSDN:
http://msdn.microsoft.com/en-IN/library/system.text.regularexpressions.regex.ismatch.aspx
Hope Its helpful.
Upvotes: 3