How ca开发者_如何学Gon I permit letters from A to Z in a textbox in a Windows Forms application. What is the source code in C#?
in your constructor or via designer:
textBox.KeyPress += new KeyPressEventHandler(textBox_KeyPress);
Then the event handler:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < 65 || e.KeyChar > 122)
{
e.Handled = true;
}
}
You can either validate the input after the user has "finished", or capture the KeyPress event and supress the event if the key isn't a letter.
If you go down the route of validation, use the TextChanged event of the textbox to check whether the .text contains any non-A-Z characters. If so, use the .SetError method of an ErrorProvider to indicate to the user that there is a problem with what they have input.
if (!Regex.IsMatch(textbox.Text, @"[a-zA-Z]"))
{
yourErrorProvider.setError(textbox, "Only A-Z accepted.");
}
In the leave event handler, check the string and show an error or force focus.
if ((Convert.ToInt32(e.KeyChar) >= 65) && (Convert.ToInt32(e.KeyChar) <= 122))
{
errorProvider1.SetError(textBox1, "OK");
errorProvider2.SetError(textBox1, "");
}
else
{
errorProvider2.SetError(textBox1, "Can not enter the numbers...");
errorProvider1.SetError(textBox1, "");
textBox1.Text = "";
}
精彩评论