如何阻止应用程序用户在文本框中输入某些文本?例如,黑名单,以便用户无法输入某些用户名等。
答案 0 :(得分:0)
当用户离开控件时,您可以检查控件的内容,看看它是否包含您不想要的内容。
Private Sub textBox1_Leave(sender As Object, e As System.EventArgs) Handles textBox1.Leave
If txtUserName.Text.Contains("YourBlacklistValue") Then
txtUserName.Text = ""
End If
End Sub
答案 1 :(得分:0)
这正是验证事件的目的。
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
Dim allowedText As String() = New String() {"Hello", "Bye"}
If allowedText.Count(Function(allowed) allowed.Equals(TextBox1.Text, StringComparison.CurrentCultureIgnoreCase)) = 0 Then
e.Cancel = True
MessageBox.Show("Invalid entry in TextBox", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
上面的代码会阻止TextBox失去焦点,除非输入数组中的两个字符串之一。
答案 2 :(得分:0)
这将很有效,在KeyPress
事件上处理它,我们可以确保它甚至没有输入。此外,它还可以在任何文本框按键事件中随处使用。另外我声明的arrList只是例如,您可以从数据库中提取列表并将项目添加到数组中,或者自己预定义一个列表...这是经过试验和测试的。
Option Strict On
Option Explicit On
Public Class Form1
Private arrList As String() = {"SillyBobbyWalt", "BobbyWalt", "SillyEngineer", "Engineers", "123", "Bobby123"}
Public Shared Function IsTextAllowed(ByVal text As String, ByVal strChar As String, ByVal arrList As Array) As Boolean
Dim blnAllowed As Boolean = True
For Each item As String In arrList
If CStr(text & strChar.ToLower) = item Then
blnAllowed = False
Exit For
End If
Next
Return blnAllowed
End Function
Private Sub txtValue_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtValue.KeyPress
If Not IsTextAllowed(CStr(txtValue.Text), e.KeyChar.ToString, arrList) Then
e.Handled = True
End If
End Sub
End Class
答案 3 :(得分:0)
您可以使用自定义控件。在内部处理KeyPress事件以捕获Enter键并检查有效的用户名是一种方法:
Public Class ValidatingTextBox
Inherits TextBox
Private BlackList As List(Of String)
Private GoodList As List(Of String)
Public Sub New()
AddHandler Me.KeyPress, AddressOf Key_Press
End Sub
Private Sub Key_Press(sender As Object, e As KeyPressEventArgs)
If e.KeyChar = Chr(Keys.Enter) Then
If BlackList.Contains(Text) OrElse Not GoodList.Contains(Text) Then
MessageBox.Show("Invalid User")
Text = ""
End If
End If
End Sub
End Class
使用这种模式,您可以轻松实现您想要的任何隐藏在您控制范围内的方法。