3

Possible Duplicate:
Restrict numbers and letters in textbox - C#

I have a textbox called TextBox1. The user should only be allowed to enter capital letters. Other characters have to be denied. How can I do that?

private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (!"ABCDEFGHIJKLMNOPQRSTUVWXYZ".Contains(Convert.ToChar(e.KeyValue)))
    {
        SendKeys.Send(Convert.ToChar(0).ToString());
    }
}
Community
  • 1
  • 1
user1531040
  • 2,143
  • 6
  • 28
  • 48
  • 3
    possible duplicate of [Restrict numbers and letters in textbox - C#](http://stackoverflow.com/questions/9601972/restrict-numbers-and-letters-in-textbox-c-sharp) or [How can I restrict the values a user enters into TextBox?](http://stackoverflow.com/questions/10142292/how-can-i-restrict-the-values-a-user-enters-into-textbox) – verdesmarald Oct 11 '12 at 11:50
  • [Regex](http://www.dotnetperls.com/regex-match) would seem to be a nicer way of doing this – dav_i Oct 11 '12 at 11:50
  • Is it windows application or web application ? – Milind Thakkar Oct 11 '12 at 11:50
  • Instead of using "ABC..." i would prefer to check the key like if(e.KeyCode < 65 || e.KeyCode > 90) e.SuppressKeyPress = true; – Tomtom Oct 11 '12 at 11:51
  • I don't think he is asking how to restrict the items entered. He is asking how to send ASCII 0 to `SendKeys()` hence it probably isn't a duplicate. – CodingWithSpike Oct 14 '12 at 14:24

4 Answers4

6

Use MaskedTextbox instead. Much easier. Your mask can be something like this: >??????????? depending on the maximal allowed length.

Matzi
  • 13,770
  • 4
  • 33
  • 50
6

Try this:

private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (!"ABCDEFGHIJKLMNOPQRSTUVWXYZ".Contains(Convert.ToChar(e.KeyValue)))
        e.Handled = true;

}
Scott Boettger
  • 3,657
  • 2
  • 33
  • 44
0

In the KeyEventArgs e there is a property called SuppressKeyPress. You can set this to true if the given key is not in your list. Then the key will not be passed to your textbox.

Tomtom
  • 9,087
  • 7
  • 52
  • 95
0

Use a MaskedTextBox. Why do you use SendKeys anyway, and what do you think the 0 character does?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272