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

Fed*_*l09 7 c# winforms

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

可能吗?我应该使用key_press事件吗?

string one = radTextBoxControl1.Text.Replace("/", "");
                string two = one.Replace("%", "");
                //more string
                radTextBoxControl1.Text = two;
Run Code Online (Sandbox Code Playgroud)

在这种模式下非常长=(

Hos*_*dir 15

我假设你试图只保留字母数字和空格字符.像这样添加一个按键事件

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您对允许的字符集使用白名单,则还需要包含控制字符.否则,像"Ctrl + C"这样的快捷键将不再起作用.`Char.IsControl(e.KeyChar)`应该对此有所帮助. (5认同)
  • 无效,因为人们可以将其复制并粘贴到文本框中。 (3认同)
  • 如果在解决方案中使用正则表达式,则退格键将不起作用,如果您需要使用退格键,那么正则表达式应该是var regex = new Regex(@"[^ a-zA-Z0-9\s [\ b]]"); (3认同)

Kid*_*lly 6

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)

VB网

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
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以使用这个:

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

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