简体   繁体   English

如何在KeyPress Event中为“,”和“。”设置例外?

[英]How to make an exception for “,” and “.” in KeyPress Event?

Note: This is not about EXCEPTIONS! 注意:这与EXCEPTIONS无关!

I'm trying to make a textbox accept everything but Symbols and Punctations... but I need to allow "," and "." 我正在尝试使文本框接受除符号和标点符号之外的所有内容……但我需要允许使用“,”和“”。 . I'm using: 我正在使用:

if (char.IsPunctuation(e.KeyChar) == true)
{
     e.Handled = true;
}

if (char.IsSymbol(e.KeyChar) == true)
{
     e.Handled = true;
}

Is there anyway to make an exception for those two Characters ( , and . ) ? 无论如何,这两个字符(和)是否有例外?

Check for these characters first: 首先检查以下字符:

if(e.KeyChar != ',' && e.KeyChar != '.')
{
    if (char.IsPunctuation(e.KeyChar))
    {
         e.Handled = true;
    }

    if (char.IsSymbol(e.KeyChar))
    {
         e.Handled = true;
    }
}

Note on style: There is no need to compare a boolean to true in order for the branch to be taken. 关于样式的注意事项:无需比较布尔值与true获取分支。

Try this: 尝试这个:

if (char.IsPunctuation(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != '.')
{
     e.Handled = true;
}

if (char.IsSymbol(e.KeyChar) && e.KeyChar != ',' && e.KeyChar != '.')
{
     e.Handled = true;
}

Or you could simply check it before all of that: 或者,您可以在所有操作之前简单地进行检查:

if( e.KeyChar != ',' && e.KeyChar != '.')
{
    if (char.IsPunctuation(e.KeyChar) )
    {
         e.Handled = true;
    }

    if (char.IsSymbol(e.KeyChar) )
    {
         e.Handled = true;
    }
}

What it does is checks if the character is punctuation/symbol and ALSO the character is NOT ',' or '.'. 它的作用是检查字符是否为标点符号/符号,以及字符是否不是“,”或“。”。 Therefor the if statement will not run if the character is a comma or period. 因此,如果字符是逗号或句点,则if语句将不会运行。

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

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