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
Related
I have successfully created the code to check for keypress but my problem is,
I want it to be in a class so that I can reuse it in other forms as well.
How do I exactly do this?
Here is the code:
Private Sub money_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles money.KeyPress
Dim allowedChars As String = "0123456789" + vbBack
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
Lets say money is the name of the textbox.
I want to call this function as well in the other forms. How do I pass the variables needed, etc.
Change it into Public:
Public Sub money_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim allowedChars As String = "0123456789" + vbBack
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
In Form2:
Public Sub form2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles form2.KeyPress
Form1.money_KeyPress(sender, e)
End Sub
Repected Sir,
I am restricting my textbox for numbers and decimal points only, i am able to get numbers and decimals only by the below function but not able to restrict making decimal points appearing twice on the input textbox. I guess If singleChars.IndexOf(KeyChar) > 0 And (Asc(KeyChar)) <> 8 has some errors and if its wrong how to solve it ?
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = myClasses.onlyCurrency(e.KeyChar)
End Sub
And my public function from class file is
Public Shared Function onlyCurrency(ByVal KeyChar As Char) As Boolean
Dim allowedChars As String
allowedChars = "0123456789."
Dim singleChars As String
singleChars = "."
If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
Return True
End If
If singleChars.IndexOf(KeyChar) > 0 And (Asc(KeyChar)) <> 8 Then
Return True
End If
Return False
End Function
Yours faithfully
Murulimadhav
You are not paying attention to what has already been entered in your TextBox, therefore your function has no idea how many decimals points have been entered. You need to either pass the TextBox's Text into your function or prescreen it before sending to your function. Something like this:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = myClasses.onlyCurrency(e.KeyChar, CType(sender, TextBox).Text)
End Sub
Public Shared Function onlyCurrency(ByVal KeyChar As Char, CurrentText As String) As Boolean
Dim allowedChars As String
allowedChars = "0123456789."
Dim singleChars As String
singleChars = "."
If KeyChar = singleChars Then
If CurrentText.Contains(singleChars) Then
Return True
End If
End If
If allowedChars.IndexOf(KeyChar) = -1 And (Asc(KeyChar)) <> 8 Then
Return True
End If
Return False
End Function
Try Like this
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Char.IsDigit(e.KeyChar) = False AndAlso e.KeyChar <> "." Then
e.Handled = True
ElseIf e.KeyChar = "." AndAlso TextBox1.Text.Trim.Contains(".") Then
e.Handled = True
Else
e.Handled = False
End If
End Sub
I am developing the Windows application.
I have a form and I am trying to validate the text box on that form.
I want to put some validation on a text box like the text box should accept only Alphabates, Didgits and comma.(No other characters like special symbols.)
As well, it should accept the Enter key when cursor is in that text box.
I am trying to write the code but some how its not working.
But its still taking special characters like <>/;'
What changes I have to made ?
here is the code...
Key Down Event
Private Sub txtOLDBuildingName_KeyDown(sender As Object, e As KeyEventArgs) Handles txtOLDBuildingName.KeyDown
' Initialize the flag to false.
nonNumberEntered = False
' Determine whether the keystroke is a number from the top of the keyboard.
If (e.KeyCode < Keys.D0 And e.KeyCode > Keys.D9) And (e.KeyCode > Keys.A And e.KeyCode < Keys.Z) Then
nonNumberEntered = True
End If
'If shift key was pressed, it's not a number.
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = True
End If
End Sub
Key Press Event
Private Sub txtOLDBuildingName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtOLDBuildingName.KeyPress
If nonNumberEntered = True Then
e.Handled = True
End If
End Sub
Delete the sub which is handling KeyDown event and replace the sub which is handling KeyPress event to this one:
ReadOnly ValidChars As String = _
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,"
Private Sub txtOLDBuildingName_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) _
Handles txtOLDBuildingName.KeyPress
e.Handled = Not (ValidChars.IndexOf(e.KeyChar) > -1 _
OrElse e.KeyChar = Convert.ToChar(Keys.Back))
End Sub
Update:
This modification is more precise, it compares the clipbard content before paste them.
ReadOnly AllowedKeys As String = _
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,"
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Handles TextBox1.KeyPress
Select Case e.KeyChar
Case Convert.ToChar(Keys.Enter) ' Enter is pressed
' Call method here...
Case Convert.ToChar(Keys.Back) ' Backspace is pressed
e.Handled = False ' Delete the character
Case Convert.ToChar(Keys.Capital Or Keys.RButton) ' CTRL+V is pressed
' Paste clipboard content only if contains allowed keys
e.Handled = Not Clipboard.GetText().All(Function(c) AllowedKeys.Contains(c))
Case Else ' Other key is pressed
e.Handled = Not AllowedKeys.Contains(e.KeyChar)
End Select
End Sub
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
I have made a textbox, which restricts character use to numbers and periods only. Nice, but now I can't enter backspace to amend any data typed in my textbox. How can I fix this?
Private Sub TextBox10_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox10.KeyPress
Dim allowedChars As String = "1234567890."
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
You can test for backspace by using
If e.KeyChar = ChrW(8) Then
MessageBox.Show("backspace!")
End If
So your whole code would become:
Private Sub TextBox10_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox10.KeyPress
Dim allowedChars As String = "1234567890."
If allowedChars.IndexOf(e.KeyChar) = -1 andalso
Not e.KeyChar = ChrW(8) Then
' Invalid Character
e.Handled = True
End If
End Sub
Similar question: How can I accept the backspace key in the keypress event?