2015-01-03 73 views
-2

这是一件简单的事情,我一直试图弄清楚一段时间,它开始恼火。我想要的只是按下按钮时,只允许某些值出现在文本框中。这是什么意思是例如只允许“abc123!”在文本框中,如果说如“w”的值,则清除文本框。Visual Basic帮助 - 在可视基本文本框中防止输入某些字符的文本限制

我尝试了诸如'如果不是正则表达式。匹配'但它只是导致我的错误。

请帮忙;)

+0

我其实需要所有的字符a-z A-z 0-9和所有的符号来工作,我想阻止诸如文或任何其他语言的字符。 –

+0

您需要在关键事件上编写代码并验证按下的键是否是有效的键。基本上你需要加强所有事件的数据输入或粘贴到您的文本框 –

回答

1

你会想要使用白名单。您允许的字符将比现有其他字符小得多。你可以通过几种方式来做到这一点。你可以在文本框中处理按键事件,如果这个值是什么,那么你执行你的代码。另一种方式可以做到这一点(如果它是一个winforms应用程序)将从文本框继承并将您的代码(那么您可以重新使用此控件)。这里是一个文本框,只允许数字输入的例子:

''' <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 

如果你只是想用一个文本框和按键事件,你可以做这样的事情。我只有两个字在我的白名单,你会想包括所有的字符,你会想包括:

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 

如果你想炭代码的列表,你可以让他们在这里:

http://www.asciitable.com/

希望这会有所帮助。 ;-)

+0

非常感谢:D –

+0

非常欢迎。 –