简体   繁体   中英

Preventing a special character input c#

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??

if (e.KeyCode == Keys.Space)
{
    // Do something here.
}

Try using a mask rule instead of doing it yourself.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM