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

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

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

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

在这种模式下非常长=(

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

 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; } } 

你可以用这个:

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

它阻止特殊字符,只接受int /数字和字符

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

我包含了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); } 

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 

你可以使用’Text Changed’事件(我相信(但不确定)这会在复制/粘贴时触发)。

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

在这个方法中有一个你想要“阻塞”的字符数组。 浏览TextBox控件的.Text的每个字符,如果在数组中找到该字符,那么您不需要它。 使用“okay”字符重建字符串,你就可以了。

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

对我来说最好的:

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

启用删除和反向键等等将更有用

我们可以使用正则表达式validation器validation它

ValidationExpression = “^ [\ SA-ZA-Z0-9] * $”

    

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