1

I am trying to stop user from entering a space key in text field. I have this code.

private void FirstNameBox_KeyDown(object sender, KeyEventArgs e)
        {
            //////////MessageBox.Show(e.KeyValue.ToString());
            //Now check to see if the key pressed is a space
            if ((e.KeyValue == 32))
            {
                MessageBox.Show("Please Enter only first name.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //Stop the key registering
                e.Handled = true;
                e.SuppressKeyPress = true;
            }
            else
            {
                //allow enter
            }
        }

Where 32 is the key value of Space Button. But this is not working now for me. I've use this code in past working perfectly with numeric entries only... trying it for space but not working. Any ideas??

LeCdr
  • 323
  • 1
  • 5
  • 18
  • You've got larger problems, actually. What about people who have multiple first names, or multi-part first names (ie, Mary Anne)? Also, there's more whitespace than just the `Space` key - what about `Tab`? Or characters that _represent_ (look like) a space, but aren't traditional whitespace (possibly found in non-ASCII sets)? – Clockwork-Muse Nov 02 '14 at 08:09
  • I have three input fields.. firstname, middlename & lastname.... they could enter other names in middle name field but for first & last name i only want them to input a single word.. – LeCdr Nov 02 '14 at 08:30
  • Ouch. Depending on what other stuff you use this for, you might run into problems with things like legal documents (wherein the first name they report isn't the same as the first name you report, because they usually don't use their full name). This can flat-out annoy your customers, too. What about things like German, where you might have `'von Trapp'` or something? Some cultures don't have "last" (or family) names. What are you doing that you mandate single first names? Problems like this is why some recommend to just use a single "name" field. – Clockwork-Muse Nov 02 '14 at 08:52

3 Answers3

1
if (e.KeyCode == Keys.Space)
{
    // Do something here.
}
mihai
  • 4,592
  • 3
  • 29
  • 42
1

Try using a mask rule instead of doing it yourself.

Here's an example for one: How to define TextBox input restrictions?

Community
  • 1
  • 1
Moti Azu
  • 5,392
  • 1
  • 23
  • 32
0

hard to say , since you're not giving much details. For example: WPF/Winforms ? which version ? why ? what are your constraints ?etc ...

In any case, you shouldn't do this manually in any case ... If you're using WPF/MVVM, a good approach would be to use validations for this.

For the above, you can have a look at the validations section in this article: The big mvvm template

Noctis
  • 11,507
  • 3
  • 43
  • 82