开发者

How to permit only letters in a textbox in a Windows Forms application?

开发者 https://www.devze.com 2022-12-22 05:23 出处:网络
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:

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 = "";
            }
0

精彩评论

暂无评论...
验证码 换一张
取 消