Key Validation

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a form where only the letters A-D are allowed in certain text boxes.
This was easy in vb6...but I don't know what to do in vb.net 2005

Thanks
 
I have a form where only the letters A-D are allowed in certain text boxes.
This was easy in vb6...but I don't know what to do in vb.net 2005

Thanks

Hey Arne,

What you want to handle is the keydown event of the textbox. In it you can
detect which key was pressed by checking the value of e.KeyCode

If e.KeyCode = Keys.A Then
e.SuppressKeyPress = True
End If
 
Try this (in an inherited TextBox):

Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
If IsValid(e.KeyChar) Then
MyBase.OnKeyPress(e)
ElseIf Char.IsControl(e.KeyChar) Then
MyBase.OnKeyPress(e)
Else
e.Handled = True
End If
End Sub

Protected Overrides Function ProcessCmdKey(ByRef msg As
System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As
Boolean
'Need to prevent pasting of invalid 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 IsValid(ch) Then
Return True
End If
Next
Return MyBase.ProcessCmdKey(msg, keyData)
End If
End If
Else
Return MyBase.ProcessCmdKey(msg, keyData)
End If
End Function

Private Function IsValid(ByVal ch As Char) As Boolean
If ch = "A"c OrElse ch = "B"c OrElse ch = "C"c OrElse ch = "D"c Then
Return True
Else
Return False
End If
End Function

/claes
 
Back
Top