I'm creating a simple application in Vb.net where I need to perform certain validations. So I want a name textbox to accept only characters from a-z and A-Z for example.
For this I wrote the following code:
Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) > 65 Or Asc(e.KeyChar) < 90 Or Asc(e.KeyChar) > 96 Or Asc(e.KeyChar) < 122 Then
e.Handled = True
End If
End If
End Sub
But somehow it is not allowing me to enter characters. When I try to enter any character it does nothing.
What causes this problem and how can I resolve it?
Alternatively, you can do something like this,
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles txtName.KeyPress
If Not (Asc(e.KeyChar) = 8) Then
Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz"
If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then
e.KeyChar = ChrW(0)
e.Handled = True
End If
End If
End Sub
or if you still want the ASCII way, try this,
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtName.KeyPress
If Not (Asc(e.KeyChar) = 8) Then
If Not ((Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90)) Then
e.KeyChar = ChrW(0)
e.Handled = True
End If
End If
End Sub
both will behave the same.
This is a more abstract approach, but still effective nonetheless. It's straightforward and can just be added to the TextChanged event. You can use it with multiple textboxes by adding their handles to the sub and using a DirectCast().
Dim allowed As String = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
For Each c As Char In TextBox.Text
If allowed.Contains(c) = False Then
TextBox.Text = TextBox.Text.Remove(TextBox.SelectionStart - 1, 1)
TextBox.Select(TextBox.Text.Count, 0)
End If
Next
Summary: If an invalid character is entered, it will immediately be deleted (most of the time the character won't be visible long enough for the user to notice).
Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
If AscW(e.KeyChar) > 64 And AscW(e.KeyChar) < 91 Or AscW(e.KeyChar) > 96 And AscW(e.KeyChar) < 123 Or AscW(e.KeyChar) = 8 Then
Else
e.KeyChar = Nothing
End If
End Sub
I hope this helps!
Am using below code to accept only letters, "-" or "'" when user is entering a person name (maybe it is simple and easier):
Private Sub txtEName1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtEName1.KeyPress
If Char.IsLetter(e.KeyChar) Or e.KeyChar = vbBack Or e.KeyChar = "-" Or e.KeyChar = "'" Then
e.Handled = False
Else
e.Handled = True
End If
End Sub
I allowed the backspace in order to allow the user to remove letters in case of mistakes
Private Sub txtStudentName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtStudentName.KeyPress
If Not Char.IsLetter(e.KeyChar) And Not e.KeyChar = Chr(Keys.Delete) And Not e.KeyChar = Chr(Keys.Back) And Not e.KeyChar = Chr(Keys.Space) Then
e.Handled = True
End If
End Sub
Related
This question already has answers here:
Multiple event handlers for the same event in VB.NET
(3 answers)
Closed 7 years ago.
can anyone help me simplify this code, because I need to extend the same way in much more line, this make my code look bulky
Private Sub tb11_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb11.KeyPress
If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
tb11.Text = e.KeyChar
End If
End Sub
Private Sub tb12_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb12.KeyPress
If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
tb12.Text = e.KeyChar
End If
End Sub
Private Sub tb13_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb13.KeyPress
If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
tb13.Text = e.KeyChar
End If
End Sub
Private Sub tb14_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tb14.KeyPress
If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
tb14.Text = e.KeyChar
End If
End Sub
Make a single event handler that runs the check then changes the sender text. Remember to cast the sender to a TextBox first though.
Private Sub TextBox_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs)
Handles tb11.KeyPress, tb12.KeyPress, tb13.KeyPress, tb14.KeyPress
If e.KeyChar >= ("1") And e.KeyChar <= ("9") Then
DirectCast(sender, TextBox).Text = e.KeyChar
End If
End Sub
Above all the event listeners functions you are checking the same condition
you can move that condition to a other method and pass your object to it
I have this Sub Statement on my Module that contains character restriction from a keypress event.
Public Sub keyFilter(ByRef e As System.Windows.Forms.KeyPressEventArgs)
If Not ((Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57) Or
(Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90) Or
(Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or
Asc(e.KeyChar) = 8 Or
Asc(e.KeyChar) = 127 Or
Asc(e.KeyChar) = 95 Or
Asc(e.KeyChar) = 32) Then
e.KeyChar = ChrW(0)
e.Handled = False
End If
End Sub
I want to call the Sub statement above to windows form keypress event by using this code but this produces an error. It says ,Value of type 'Char' cannot be converted to 'System.Windows.Forms.KeyPressEventArgs
Private Sub txtTableName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTableName.KeyPress
Call keyFilter(e.KeyChar)
End Sub
Can you tell me what is/are the problem with my codes? Is it really possible to call a keypress event function in windows form? Thanks.
Try to change this line :
Call keyFilter(e.KeyChar)
to this :
Call keyFilter(e)
KeyFilter expect KeyPressEventArgs as parameter, but you passed e.KeyChar which is a Char. You should pass e which is KeyPressEventArgs instead.
KeyFilter() function takes an argument of type KeyPressEventArgs, you should replace the calling statement with Call keyFilter(e), do not pass e.KeyChar..
Try this...
Public Sub keyFilter(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
If Not ((Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57) Or
(Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90) Or
(Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or
Asc(e.KeyChar) = 8 Or
Asc(e.KeyChar) = 127 Or
Asc(e.KeyChar) = 95 Or
Asc(e.KeyChar) = 32) Then
e.KeyChar = ChrW(0)
e.Handled = False
End If
End Sub
Private Sub txtTableName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTableName.KeyPress
Call keyFilter(sender, e)
End Sub
I have 4 textboxes which are used to store IP Addresses. I want to automate the selection of the textboxes by inputting the .(DOT) character; I want also this character to be deleted right after having been input. I have been able to get the auto-selection functionality, but not the character deletion part. Here is my code:
If e.KeyCode = Keys.OemPeriod Then
TextBox2.Focus()
End If
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) = 46 Then 'It does not matter how you select the character
TextBox2.Focus()
e.Handled = True 'To avoid the character to be written (i.e., delete the DOT)
End If
End Sub
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Asc(e.KeyChar) = 46 Then
TextBox3.Focus()
e.Handled = True
End If
End Sub
Private Sub TextBox3_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox3.KeyPress
If Asc(e.KeyChar) = 46 Then
TextBox4.Focus()
e.Handled = True
End If
End Sub
i have the following code:
Private Sub TxtPStof_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtPStof.KeyPress
e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".")
End Sub
which allows only digits and . in my textbox, however i also need to be able to delete values using the backspace or the delete button.
Is this possible?
Thanks! :)
This is the wrong approach.
It’s universally agreed that restricting the user’s input is bad for the user experience, and you will invariably fail to handle special cases (what about Ctrl+V, for instance? Ah, you forgot about that. Everybody does).
Instead, .NET offers the Validating event for validating user input. You should intercept that event, not the keypress. Do allow users to enter text however they want; in particular, allow them to make mistakes (e.g. mistyping) without interruption – that would be extremely disruptive and not helpful.
Then, once they’re finished (because input focus leaves the control), do an input validation in one go.
While I totally agree with the answer from Konrad Rudolph
(It's really a messy affair to handle the user input in the KeyPress event)
I wish to give an answer at your question.
The MSDN in the KeyPress docs states that The KeyPress event is not raised by noncharacter keys. This means that you don't get the Delete key, but only the BackSpace key. You could handle this situation with this little change to your event handler
Private Sub TxtPStof_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TxtPStof.KeyPress
if e.KeyChar <> ControlChars.Back then
e.Handled = Not (Char.IsDigit(e.KeyChar) Or e.KeyChar = ".")
end if
End Sub
If Char.IsLetterOrDigit(e.KeyChar) Or e.KeyChar = ControlChars.Back Or e.KeyChar = "." Then
e.Handled = False
Else
e.Handled = True
End If
this code works fine for me.
If Not ((Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57) Or Asc(e.KeyChar) = 46 Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 127) Then
e.KeyChar = ""
e.Handled = False
End If
try this one:
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
If Not (Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 46) Then e.Handled = True
End If
Private Sub textbox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textbox.KeyPress
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
This should do what you want it to do.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim NumString = "0123456789.-"
If Not NumString.Contains(e.KeyChar) Then
If Asc(e.KeyChar) <> 8 Then 'BackSpace is allowed
e.KeyChar = ""
End If
Else
If e.KeyChar = "-" Then
If Len(Trim(TxtDcrAmt.Text)) > 0 Then
e.KeyChar = ""
End If
End If
If e.KeyChar = "." Then
If TxtDcrAmt.Text.Contains(".") Then
e.KeyChar = ""
End If
End If
If TxtDcrAmt.Text.Contains(".") Then
Dim TLen As Integer = 0
TLen = TxtDcrAmt.Text.IndexOf(".") + 2
If Len(Trim(TxtDcrAmt.Text)) > TLen Then
e.KeyChar = ""
End If
End If
End If
End Sub
Put this on keypress event. This allows dots and numbers only
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 46 Or Asc(e.KeyChar) > 57 Or (Asc(e.KeyChar) < 48 And Asc(e.KeyChar) > 46) Then
e.Handled = True
End If
End If
I found this code for making my textbox only accept numbers.
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
But... the user can't delete the numbers using the backspace button. How do I do then?
Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
'Dim allowedChars As String = "0123456789"
'If allowedChars.IndexOf(e.KeyChar) = -1 Then
' ' Invalid Character
' e.Handled = True
'End If
'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
' e.Handled = True
'End If
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
End Sub
You also need to handle pasted text (there may not be a keypress). The best way to do this is with a MaskedTextBox.
voldemort
i develop your first code to allow the user to delete too.
Here is the code :
Dim BACKSPACE As Boolean
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Back Then
BACKSPACE = True
Else
BACKSPACE = False
End If
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If BACKSPACE = False Then
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End If
End Sub
I Hope My Code Was Useful To You :)
Use this code, it will help you
Public Function OnlyDigitsOnKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Try
If System.Char.IsDigit(e.KeyChar) = False And e.KeyChar <> Microsoft.VisualBasic.Chr(8) And e.KeyChar <> Microsoft.VisualBasic.Chr(46) Or (InStr(sender.text, ".") > 0 And e.KeyChar = Microsoft.VisualBasic.Chr(46))
Then
e.Handled = True
End If
Catch ex As Exception
Common.ErrorHandler(ex)
End Try
End Function
When I have had the requirement of an input which only accepts numbers, I have typically used the NumericUpDown class. It handles limits and decimals too.
Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
Dim allowedChars As String = "."
'If allowedChars.IndexOf(e.KeyChar) = -1 Then
' ' Invalid Character
' e.Handled = True
'End If
'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
' e.Handled = True
'End If
If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False And allowedChars.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End Sub
Here is some code that I wrote. It allows the user to delete, and the user can make the textbox blank if they desire. It handles when the user types a disallowed character, and it also handles when the user pastes text into the textbox. If the user pastes a string into the box that is a mix of valid and invalid characters, the valid characters will appear in the textbox, and the invalid characters will not.
It also has logic in place to ensure that the cursor behaves normally. (A problem with setting the text to a new value is that the cursor is moved back to the beginning. This code tracks the original position, and makes adjustments to account for any invalid characters that are removed.)
This code can be placed in the TextChaned event of any textbox. Be sure to change the name from TextBox1 to match your textbox.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
Dim selStart As Integer = TextBox1.SelectionStart
Dim selMoveLeft As Integer = 0
Dim newStr As String = "" 'Build a new string by copying each valid character from the existing string. The new string starts as blank and valid characters are added 1 at a time.
For i As Integer = 0 To TextBox1.Text.Length - 1
If "0123456789".IndexOf(TextBox1.Text(i)) <> -1 Then 'Characters that are in the allowed set will be added to the new string.
newStr = newStr & TextBox1.Text(i)
ElseIf i < selStart Then 'Characters that are not valid are removed - if these characters are before the cursor, we need to move the cursor left to account for their removal.
selMoveLeft = selMoveLeft + 1
End If
Next
TextBox1.Text = newStr 'Place the new text into the textbox.
TextBox1.SelectionStart = selStart - selMoveLeft 'Move the cursor to the appropriate location.
End Sub
Note - if you have to do this for a bunch of textboxes, you can make a general purpose version of this by creating a sub that accepts a reference to a textbox as a parameter. Then you only need to call the sub from the TextChanged event.
Private Sub TMarksTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TMarksTextBox.KeyPress
If e.KeyChar < "0" OrElse e.KeyChar > "9" AndAlso e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub