简体   繁体   English

防止特殊字符输入C#

[英]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. 其中32是“空格键”的键值。 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? 这是一个示例: 如何定义TextBox输入限制?

hard to say , since you're not giving much details. 很难说,因为您没有提供太多细节。 For example: WPF/Winforms ? 例如: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. 无论如何,在任何情况下都不应该手动执行此操作...如果您使用的是WPF / MVVM,则一种好的方法是对此进行验证。

For the above, you can have a look at the validations section in this article: The big mvvm template 对于以上内容,您可以看一下本文的验证部分: 大的mvvm模板

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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