textbox does not allow for backspace to be pressed? - vb.net

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?

Related

How to create a class to check for keypress

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

VB.Net VS 2008 validating textbox.text for one decimal point only

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

How to avoid taking special characters in textbox of a Windows application

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

Only accept digits for textbox

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

textbox.clear can somebody check where it is wrong?

Im making a textbox which wont allow the user to use spaces but rather then clear the textbox it simply deleats the last character (which is the space) my code dosnt work can sombody look at it please?
Private Sub Textbox1_keyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
Dim UNDONE_TEXT As String
If e.KeyCode = Keys.Space Then
UNDONE_TEXT = ((TextBox1.Text) - 1)
TextBox1.Clear()
TextBox1.Text = UNDONE_TEXT
MsgBox("Invalid character. No spaces Permited...")
End If
End Sub
this returns 3????
UPDATE:
Private Sub Textbox1_keyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
Dim UNDO_TEXT As String
If e.KeyCode = Keys.Space Then
UNDO_TEXT = TextBox1.Text
TextBox1.Clear()
TextBox1.Text = UNDO_TEXT
TextBox1.Text.TrimEnd()
MsgBox("Invalid character. No spaces Permited...")
End If
End Sub
only now the focus is on the entire textbox when returned after MSGbox?
UNDONE_TEXT = left(TextBox1.Text, len(TextBox1.text)-1)
I'm no VBA expert, but would TextBox1.Text.Trim() be what you're looking for? This removes spaces at the beginning and at the end of a string. Possibly, you could try TrimEnd(). I don't know if that exists in VBA, it does in VB.NET:
Private Sub Textbox1_keyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
Dim UNDO_TEXT As String
If e.KeyCode = Keys.Space Then
TextBox1.Text = TextBox1.Text.TrimEnd()
MsgBox("Invalid character. No spaces Permited...")
End If
End Sub