我需要从文本框中排除特殊字符(%,&,/,",'
等)
有可能吗?我应该使用key_press事件吗?
string one = radTextBoxControl1.Text.Replace("/", "");
string two = one.Replace("%", "");
//more string
radTextBoxControl1.Text = two;
在这种模式下非常长=(
答案 0 :(得分:13)
我假设你试图只保留字母数字和空格字符。像这样添加一个按键事件
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;
}
}
答案 1 :(得分:4)
你可以用这个:
private void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar);
}
它会阻止特殊字符,只接受int / numbers和characters
答案 2 :(得分:2)
以下代码仅允许数字,字母,退格和空格。
我包含了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
答案 3 :(得分:0)
您可以使用&#39; Text Changed&#39;事件(我相信(但不确定)这会在复制/粘贴时被触发)。
当事件被触发时,请调用方法,例如,PurgeTextOfEvilCharacters()。
在这个方法中有一个你想要的字符数组&#34; block&#34;。浏览TextBox控件的.Text的每个字符,如果在您的数组中找到该字符,那么您不需要它。使用&#34; okay&#34;重建字符串。角色,你很高兴。
我打赌那里有更好的方法,但这对我来说似乎没问题!
答案 4 :(得分:0)
对我来说最好:
void textBoxSample_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = Char.IsPunctuation(e.KeyChar) ||
Char.IsSeparator(e.KeyChar) ||
Char.IsSymbol(e.KeyChar);
}
启用删除和退格键等等更有用
答案 5 :(得分:0)
我们可以使用正则表达式验证器验证它
ValidationExpression =&#34; ^ [\ SA-ZA-Z0-9] * $&#34;
swiftmailer:
transport: smtp
host: smtp-relay.gmail.com
port: 587
encryption: tls
sender_address: support@example.com
你也可以在这里看到演示 https://www.neerajcodesolutions.com/2018/05/how-to-restrict-special-characters-in.html
答案 6 :(得分:0)
另一种排除各种字符(例如%,&,',A,b,2)的方法是在TextBox KeyPress事件处理程序中使用以下内容:
e.Handled = "%&'Ab2".Contains(e.KeyChar.ToString());
要将双引号包括在排除列表中,请使用:
e.Handled = ("%&'Ab2"+'"').Contains(e.KeyChar.ToString());
注意:这是区分大小写的。