这是一个简单的事情,我一直试图弄清楚一段时间,并开始惹恼。我想要的只是当按下按钮时,只允许某些值出现在文本框中。这意味着例如只允许“abc123!”在文本框中,如果说“w”之类的值,则清除文本框。
我尝试过“If Not Regex.Match”之类的内容,但这只会导致我出错。
请帮助;)
答案 0 :(得分:1)
您可能想要使用白名单。您允许的字符将比现有的其他字符小得多。你可以通过几种方式做到这一点。您可以在文本框中处理按键事件,如果该值是任何值,则执行代码。你可以这样做的另一种方式(比如说它是一个winforms应用程序)将继承文本框并将你的代码放在那里(然后你可以重新使用这个控件)。以下是仅允许数字输入的TextBox示例:
''' <summary>
''' Text box that only accepts numeric values.
''' </summary>
''' <remarks></remarks>
Public Class NumericTextBox
Inherits TextBox
Private Const ES_NUMBER As Integer = &H2000
Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
Get
Dim params As CreateParams = MyBase.CreateParams
params.Style = params.Style Or ES_NUMBER
Return params
End Get
End Property
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
'Prevent pasting of non-numeric characters
If keyData = (Keys.Shift Or Keys.Insert) OrElse keyData = (Keys.Control Or Keys.V) Then
Dim data As IDataObject = Clipboard.GetDataObject
If data Is Nothing Then
Return MyBase.ProcessCmdKey(msg, keyData)
Else
Dim text As String = CStr(data.GetData(DataFormats.StringFormat, True))
If text = String.Empty Then
Return MyBase.ProcessCmdKey(msg, keyData)
Else
For Each ch As Char In text.ToCharArray
If Not Char.IsNumber(ch) Then
Return True
End If
Next
Return MyBase.ProcessCmdKey(msg, keyData)
End If
End If
ElseIf keyData = (Keys.Control Or Keys.A) Then
' Process the select all
Me.SelectAll()
Else
Return MyBase.ProcessCmdKey(msg, keyData)
End If
End Function
End Class
如果您只想使用TextBox和KeyPress事件,您可以执行以下操作。我的白名单中只有两个字符,你想要包含你想要包含的所有字符:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
' Test white list, this is only 0 and 1 which are ASCII 48 and 49
Dim allowedChars() As String = {Chr(48), Chr(49)}
If allowedChars.Contains(e.KeyChar) Then
' Setting handled to true stops the character from being entered, remove this or execute your code
' here that you want
e.Handled = True
End If
End Sub
如果你想要一个char代码列表,你可以在这里找到它们:
希望这会有所帮助。 ; - )