当用户使用/:*?"<> |时,我有一个文本框,他无法插入符号。
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If e.KeyChar = ">"c Or e.KeyChar = "<"c Or e.KeyChar = "\"c Or e.KeyChar = "/"c Or e.KeyChar = ":"c Or e.KeyChar = "*"c Or e.KeyChar = "?"c Or e.KeyChar = "|"c Or e.KeyChar = "?"c Or e.KeyChar = """"c Then
e.Handled = True
MessageBox.Show("You cant use \/:*?""" & "<" & ">" & "|", "WARNING !!!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End Sub
但我如何检查if是否在文本框中检查它们是否为此符号之一&#34; /:*?&#34;&lt;&gt; |&#34; ?因为有复制/粘贴.........
我尝试测试。形成这段代码:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If flag Then
Return
End If
flag = True
Dim InvalidChars = "/:*?""<>|".ToCharArray()
For i As Integer = 0 To InvalidChars.Length - 1
TextBox1.Text = TextBox1.Text.Replace(InvalidChars(i).ToString(), "")
Next
flag = False
End Sub
但是没有声明旗帜,我不明白bool .....
对于另一个我尝试使用相同的表格
Imports System.Text.RegularExpressions
公共类测试
Private Sub test_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox2.Text = Regex.Replace(TextBox1.Text, "/:*?\<>", "")
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
结束班
textbox1与textbox2相同
答案 0 :(得分:1)
有几种方法:
TextChanged
事件检测新文本然后
Regex
来检测无效字符。为TextBox添加TextChanged
事件处理程序。在处理程序中添加以下代码:
if (flag) return;
flag = true;
var InvalidChars = "/:*?\"<>|".ToCharArray();
for (int i = 0; i < InvalidChars.Length; i++)
txtYourTextBox.Text = txtYourTextBox.Text.Replace(InvalidChars[i].ToString(), "");
flag = false;
flag
是一个表单级bool
变量,用于阻止递归TextChanged
事件。
要对Regex
执行相同操作,请在TextChanged
事件处理程序中添加以下代码:
txtYourTextBox.Text = Regex.Replace(txtYourTextBox.Text, "[/:*?\"<>|]", "");
Regex
命名空间中提供了 System.Text.RegularExpressions
类。请注意,在这种情况下,我没有使用flag
,因为这只会导致重入一次。