tags:

views:

87

answers:

4

to permit letters from A to Z what is the source code in C#?

A: 

on leave event check string and show error or force focus

Andrey
A: 

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.

M.A. Hanin
KeyPress is bad idea because wrong string can be copy-pasted
Andrey
Or you can do the keypress check *and* validation on leaving the box... Better to prevent the user from doing something wrong than to only tell them after the fact.
Jacob G
A: 

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.");
}
Daniel I-S
+1  A: 

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;
    }
}
adharris
Bear in mind, this will only work while the user is typing - it will not work if the user attempts to paste in unacceptable values.
Daniel I-S