How to avoid taking special characters in textbox of a Windows application - vb.net

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

Related

Is there anyway to change ComboBox key inputs in VB.NET?

I have a combobox in my Userform. Whilst this is in focus, I am wanting to use the keyboard for WASD controls. However, I find that when I press WASD the Combobox is bringing up values beginning with these letters. Also, the arrow keys are cycling through the options as well.
Is there anyway to restrict these commands?
I have tried
Tool.AutoCompleteMode = AutoCompleteMode.None
This does not stop is doing this. Does anybody have any clue how I could access more specific controls to stop this kind of autofill happening?
If you have only the Combobox control in your form and no other input controls, such as textbox, you can try the following code:
Please set e.Handled = True in the KeyPress event of the Combobox.
Private Sub ComboBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
If you have some input controls, you want to retain the editing function, and you want to not interfere with the KeyPress event of the form.
You could refer to the following steps.
(1) Please set Me.KeyPreview = False in the KeyDown event of each input control.
(2) Please set e.Handled = True in the KeyPress event of ComboBox1.
(3) When double-clicking the form to enter WASD, you can set ComboBox1.Focus().
Sample code:
Public Class Form1
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles MyBase.KeyPress
'edit your code
Dim offset As Integer = 10
If e.KeyChar = "a" Then
PictureBox1.Location = New Point(PictureBox1.Location.X - offset, PictureBox1.Location.Y)
ElseIf e.KeyChar = "w" Then
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - offset)
ElseIf e.KeyChar = "s" Then
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + offset)
ElseIf e.KeyChar = "d" Then
PictureBox1.Location = New Point(PictureBox1.Location.X + offset, PictureBox1.Location.Y)
End If
e.Handled = True
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.KeyPreview = True
End Sub
Private Sub Form1_DoubleClick(sender As Object, e As EventArgs) Handles MyBase.DoubleClick
ComboBox1.Focus()
Me.KeyPreview = True
End Sub
Private Sub ComboBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ComboBox1.KeyPress
e.Handled = True
End Sub
Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
Me.KeyPreview = False
End Sub
End Class
Result:

textbox with numbers only but also pasting, copying, and selecting

I'm quite new in VB and got stuck on (i think) easy problem. I have a text box thats allows only numbers:
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
from 1 to 9. But this box doesnt allows me to paste, copy, and select text...how can i change it? I know that KeyCode for Control is 17, and for 'V' is 86, but have no idea how to use it...
thanks for any help
The issue with KeyPress is that it calls only one KeyPress at a time. Hence multiple selections such as Ctrl+V, Ctrl+C would not work. Instead of flagging it under KeyPress, call the TextChanged. Add the below mentioned and the issue should be resolved. Copy, Paste and Selecting would now work as normal.
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
TextBox2.Text = System.Text.RegularExpressions.Regex.Replace(TextBox2.Text, "[^\d]", "") 'Removes all character except numbers
TextBox2.Select(TextBox2.Text.Length + 1, 1) 'To bring the textbox focus to the right
End Sub
If you necessarily want a TextBox you could combine the KeyDown and KeyPress events in order to block anything that isn't numbers while manually allowing Copy, Paste, Cut, etc.
Imports System.Text.RegularExpressions
Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
e.Handled = Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False 'Verify if input is a number or a control character (such as Backspace).
End Sub
Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
e.SuppressKeyPress = True 'Start by blocking all key presses.
Select Case e.KeyData 'In order to not block some standard keyboard shortcuts.
Case Keys.Control Or Keys.C 'Copy
TargetTextBox.Copy()
Case Keys.Control Or Keys.X 'Cut
TargetTextBox.Cut()
Case Keys.Control Or Keys.V 'Paste
TargetTextBox.Paste()
TargetTextBox.Text = Regex.Replace(TextBox2.Text, "[^\d]", "")
Case Keys.Control Or Keys.A 'Select all.
TargetTextBox.SelectAll()
Case Else
e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
End Select
End Sub
EDIT: Pardon the unintentional similar Regex, Arun Kumar.
This worked for me , write the below code on textbox keypress event
Try
If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) AndAlso (e.KeyChar <> Chr(22)) Then
MsgBox("Please enter numeric values", MsgBoxStyle.Information)
e.Handled = True
End If
Catch ex As Exception
pObj.WriteErrorLog(Me.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex, True)
End Try

VB.net move between textboxes by keyboard arrow

I Have VB.net application form with 10 horizontal text boxes . I need to move between text boxes with right And Left Keyboard Arrow . Also I need Make textBoxes Format To Be Like This 0.00
In addition to webdad3's answer.
Private Sub Form1_KeyDown(ByVal sender as Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
Dim tb as TextBox = TryCast(me.ActiveControl, TextBox)
If tb IsNot Nothing Then
Select Vase e.KeyCode
Vase Keys.Right, Keys.Left
dim forward as boolean = e.KeyCode = Keys.Right
me.SelectNextControl(Me, forward, True, True, true)
e.Handled = true
End Select
End If
End Sub
Don't forget to set Form.KeyPreview to true (via Forms Designer)
For the second part:
There are many, many different ways to format the text of a textbox.
The best solution would be to use DataBindings (complex topic, read a book about it.)
Public Class Form1
Public Property Price as Decimal
' call this code once
Private Sub InitControls()
Price = 3.45
me.txtPrice.DataBindings.Add(
"Text", Me, "Price", True,
DataSourceUpdateMode.OnPropertyChanged, Nothing, "0.00"
)
End Sub
End Class
I got the following code from the following link:
http://social.msdn.microsoft.com/Forums/windows/en-US/ffeeea42-f6ba-420f-827e-74879fd29b26/how-to-
detect-arrow-keys-in-vbnet?forum=winforms
Private Sub Form1_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
' Sets Handled to true to prevent other controls from
' receiving the key if an arrow key was pressed
Dim bHandled As Boolean = False
Select Case e.KeyCode
Case Keys.Right
'do stuff
e.Handled = True
Case Keys.Left
'do other stuff
e.Handled = True
Case Keys.Up
'do more stuff
e.Handled = True
Case Keys.Down
'do more stuff
e.Handled = True
End Select
End Sub

textbox does not allow for backspace to be pressed?

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?

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