C# 如何阻止或限制文本框中的特殊字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19524105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:11:37  来源:igfitidea点击:

How to block or restrict special characters from textbox

c#winforms

提问by Federal09

I need exclude special characters (%,&,/,",'etc ) from textbox

我需要%,&,/,",'从文本框中排除特殊字符(等)

Is it possible? Should I use key_press event?

是否可以?我应该使用 key_press 事件吗?

string one = radTextBoxControl1.Text.Replace("/", "");
                string two = one.Replace("%", "");
                //more string
                radTextBoxControl1.Text = two;

in this mode is very very long =(

在这种模式下非常非常长=(

采纳答案by Hossain Muctadir

I am assuming you are trying to keep only alpha-numeric and space characters. Add a keypress event like this

我假设您试图仅保留字母数字和空格字符。添加这样的按键事件

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    var regex = new Regex(@"[^a-zA-Z0-9\s]");
    if (regex.IsMatch(e.KeyChar.ToString()))
    {
        e.Handled = true;
    }
}

回答by Andrew Mack

You could use the 'Text Changed' event (I BELIEVE (but am not sure) that this gets fired on a copy/paste).

您可以使用“文本更改”事件(我相信(但不确定)这会在复制/粘贴时触发)。

When the event is triggered call a method, let's say, PurgeTextOfEvilCharacters().

当事件被触发时调用一个方法,比方说,PurgeTextOfEvilCharacters()。

In this method have an array of the characters you want to "block". Go through each character of the .Text of the TextBox control and if the character is found in your array then you don't want it. Rebuild the string with the "okay" characters and you're good to go.

在这个方法中有一个你想要“阻止”的字符数组。遍历 TextBox 控件的 .Text 的每个字符,如果在数组中找到该字符,则不需要它。用“okay”字符重建字符串,你就可以开始了。

I'm betting there's a better way, but this seems okay to me!

我打赌有更好的方法,但这对我来说似乎没问题!

回答by Francis Acosta

you can use this:

你可以使用这个:

private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
    }

it blocks special characters and only accept int/numbers and characters

它阻止特殊字符并且只接受整数/数​​字和字符

回答by Hisham

the best for me:

最适合我:

void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = Char.IsPunctuation(e.KeyChar) ||  
                      Char.IsSeparator(e.KeyChar) || 
                      Char.IsSymbol(e.KeyChar);
    }

it will be more usefull to enable delete and backsapce Keys ...etc

启用 delete 和 backsapce Keys ... 等会更有用

回答by CrazyPaste

The code below allows only numbers, letters, backspace and space.

下面的代码只允许数字、字母、退格和空格。

I included VB.net because there was a tricky conversion I had to deal with.

我包含了 VB.net,因为我必须处理一个棘手的转换。

C#

C#

private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = e.KeyChar != (char)Keys.Back && !char.IsSeparator(e.KeyChar) && !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
}

VB.net

VB.net

Private Sub textBoxSample_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBoxSample.KeyPress
    e.Handled = e.KeyChar <> ChrW(Keys.Back) And Not Char.IsSeparator(e.KeyChar) And Not Char.IsLetter(e.KeyChar) And Not Char.IsDigit(e.KeyChar) 
End Sub

回答by Pooja

we can validate it using regular expression validator

我们可以使用正则表达式验证器来验证它

ValidationExpression="^[\sa-zA-Z0-9]*$"

ValidationExpression="^[\sa-zA-Z0-9]*$"

<asp:TextBox runat="server" ID="txtname" />
        <asp:RegularExpressionValidator runat="server" ControlToValidate="txtname"
            ForeColor="Red" SetFocusOnError="true" Display="Dynamic"
            ErrorMessage=" Restrict for special characters" ID="rfvname"
            ValidationExpression="^[\sa-zA-Z0-9]*$">

        </asp:RegularExpressionValidator>

you can see also demo here https://www.neerajcodesolutions.com/2018/05/how-to-restrict-special-characters-in.html

你也可以在这里看到演示 https://www.neerajcodesolutions.com/2018/05/how-to-restrict-special-characters-in.html

回答by StuKay

Another way to exclude a varied selection of characters such as %,&,',A,b,2 would be to use the following in the TextBox KeyPress event handler:

排除各种字符选择(例如 %,&,',A,b,2)的另一种方法是在 TextBox KeyPress 事件处理程序中使用以下内容:

e.Handled = "%&'Ab2".Contains(e.KeyChar.ToString());

To include a double quote to the exclusion list use:

要在排除列表中包含双引号,请使用:

e.Handled = ("%&'Ab2"+'"').Contains(e.KeyChar.ToString());

Note: This is case sensitive.

注意:这是区分大小写的。