textbox with numbers only but also pasting, copying, and selecting - vb.net

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

Related

KeyPress Event in Visual Basic?

I think this is possible, but I don't know... I want to check when the key A is pressed to move the player to the left, but for now just a messagebox.
Here is all the code I could find on the internet, it didn't work...
Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
If e.KeyCode = Keys.A Then
MsgBox("Left")
End If
End Sub
I am not asking how to do things when you enter stuff in a textbox, I'm asking how to run a event when you press a key.
Try this...
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) = 97 Or Asc(e.KeyChar) = 65 Then
MsgBox("hello")
End If
End Sub
This should work. 97 is 'a' and 65 is 'A' in ASCII.
Try this
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyCode = Keys.A Then
MsgBox("Left")
End Sub
or
Private Sub textBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) _
Handles textBox1.KeyDown
If e.KeyCode = Keys.A Then
MsgBox("Left")
end if
End Sub
You probably want to set the form's KeyPreview property to true.
Doing this makes sure the form sees all key events even if one of
its child controls
Use the KeyEventArgs.KeyData property to see what key was pressed.
KeyCode , KeyData and KeyValue are members of
System.Windows.Forms.KeyEventArgs in the KeyUp and KeyDown events
only.
They actually simplified this from VB6.The new way with VB 2017 is...
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtProblem.KeyPress
If e.KeyCode = "a" or e.KeyCode = "A" Then
MsgBox("Left")
End If
End Sub
So, I got one step in the right direction maybe it will help. I'm trying to give control of the paddle to the player in a game of pong and found if textbox1 is highlighted or "has focus" then these commands will execute and I can move the paddle around the screen. The problem is there is also a textbox filling up with letters in the corner of the screen as this happens I'm not sure how to get rid of just yet. Perhaps it will be useful though.
Private Sub
Textbox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Asc(e.KeyChar) = 97 Then 'a
Paddle.Location = New Point(Paddle.Location.X - 10, Paddle.Location.Y)
End If
If Asc(e.KeyChar) = 119 Then 'w
Paddle.Location = New Point(Paddle.Location.X, Paddle.Location.Y - 10)
End If
If Asc(e.KeyChar) = 100 Then 'd
Paddle.Location = New Point(Paddle.Location.X + 10, Paddle.Location.Y)
End If
If Asc(e.KeyChar) = 115 Then 's
Paddle.Location = New Point(Paddle.Location.X, Paddle.Location.Y + 10)
End If
End Sub
Also, you can use this command to give focus to the textbox from a different event
Public Sub ControlSetFocus(control As Control)
If Control.CanFocus Then
control.Focus()
End If
End Sub
This works for me
If e.KeyChar = Convert.ToChar("a") Then
MsgBox(Convert.ToChar("a") +"enter key pressed ")
End If
Also you can use numbers and uppercase in ""

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

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

How do you detect simultaneous keypresses such as "Ctrl + T" in VB.NET?

I am trying to detect the keys "Control" and "t" being pressed simultaneously in VB.NET. The code I have so far is as follows:
Private Sub frmTimingP2P_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyValue = Keys.ControlKey And e.KeyValue = Keys.T Then
MessageBox.Show("Ctrl + T")
End If
End Sub
I can detect one key or the other by removing the and statement and the second keyvalue statement, but I don't really get anything when I try this. Is there another method?
Thanks
First of all, And in your code should be AndAlso since it’s a logical operator. And in VB is a bit operator. Next, you can use the Modifiers property to test for modifier keys:
If (e.KeyCode And Not Keys.Modifiers) = Keys.T AndAlso e.Modifiers = Keys.Control Then
MessageBox.Show("Ctrl + T")
End If
The e.KeyCode And Not Keys.Modifiers in the first part of the condition is necessary to mask out the modifier key.
If e.Modifiers = Keys.Ctrl can also be written as If e.Control.
Alternatively, we can collate these two queries by asking directly whether the combination Ctrl+T was pressed:
If e.KeyCode = (Keys.T Or Keys.Ctrl) Then …
In both snippets we make use of bit masks.
Private Sub frmMain_Zaporka_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
Select Case e.KeyData
Case (Keys.Control + Keys.Shift + Keys.F12)
MsgBox("Control + Shift + F12")
Case (Keys.Escape)
Me.Close()
End Select
' or
If e.KeyCode = Keys.F12 AndAlso e.Modifiers = (Keys.Control Or Keys.Shift) Then
MsgBox("Control + Shift + F12")
ElseIf e.KeyCode = Keys.Escape Then
Me.Close()
End If
' or
Select Case e.KeyCode
Case (Keys.F12 And e.Control And e.Shift)
MsgBox("Control + Shift + F12")
Case (Keys.Escape)
Me.Close()
End Select
End Sub
I had the same problem, but for me to get this to work I had to set the forms KeyPreview property to true. In Visual studio you can change this in the Forms [Design] Property window or changing the property on load.
Private Sub frmTimingP2P_Load(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles MyBase.Load
Me.KeyPreview = True
End Sub
then use by using:
Private Sub frmTimingP2P_KeyDown(ByVal Sender As Object, ByVal e As _
System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If (e.KeyCode = Keys.T AndAlso e.Modifiers = Keys.Control) Then
MessageBox.Show("Ctrl + T")
End If
End Sub
or other program logic as provided in the answers above.
I'll save you from the long code.
Here:
If e.Control And e.Alt And e.KeyCode = Keys.G Then
MsgBox("Control Alt G")
End If
I dont have vb.net installed right now but try this on your keydown or keypress event:
If e.KeyCode = Keys.T AndAlso e.Control = True Then
MsgBox("Ctrl + T")
End If
I actually found through experimentation that the KeyPreview setting is irrelevant when code is processed through the "KeyDown" or "KeyUp" routines we add into our code. Perhaps the automatic inbuilt code for keypress takes the KeyPreview setting into account, but ours does not even have to consider it.
I found the best approach is the one shown in KuroMoro's answer, using e.KeyData plus various "Case Statements".
The following works beautifully to insert symbols into a textbox when certain keys are pressing with the Control key simultaneously.
Private Sub Comments_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Comment.KeyDown, Response.KeyDown
Select Case e.KeyData
Case (Keys.S + Keys.Control)
SendKeys.Send("♠")
Case (Keys.H + Keys.Control)
SendKeys.Send("♥")
Case (Keys.D + Keys.Control)
SendKeys.Send("♦")
Case (Keys.C + Keys.Control)
SendKeys.Send("♣")
End Select
End Subcode
Like Chris Raisin's approach, I use the KeyUp event. Otherwise, pressing the Control key can trigger an action before you press a second key. Here's an example of my code to test for CTRL-A in a listview control named lvSpectra:
Private Sub lvwSpectra_KeyUp(sender As Object, e As KeyEventArgs) Handles lvwSpectra.KeyUp
If e.Control And e.KeyCode = Keys.A Then
' Do something
End If
End Sub

Validation of Decimal in text Box

I am trying to validate wether a number is a decimal in Visual Basic. The results I get when the number is valid the msgBox shows. When it is not valid, I don't receive the msgBox and the program crashes with an error message that number has to be less than infinity.
I tried adding another If Not IsNumeric(txt1.text) then -- But received the same results.
Where did i go wrong?
If IsNumeric(txt1.text) Then
msgBox("good")
Else
msgBox("not good")
End If
Try using Double.TryParse or Decimal.TryParse instead of IsNumeric.
Dim result as Double = 0.0
if Double.TryParse(txt1.text, result) then
' valid entry
else
' invalid entry
end if
I have just had to write a function which restricts input to a text box to valid decimal values, and I came up with the following:
Private Sub validateDecimalTextBox(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) handles myTextBox.keyPress
Dim textBox As TextBox = DirectCast(sender, TextBox)
If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And textBox.Text.IndexOf(".") < 0) Or (e.KeyChar = "-" And textBox.Text.Length = 0)) Then
e.Handled = True
End If
End Sub
This should restrict user input to decimal values, allowing negative values as well.
If you restrict the user inputs then when you get the value out from the text box you can be more confident that it is valid.
This solution is not complete however as it would allow a user to enter just "-" in the text box which would (presumably) not be a valid input for you. Therefore you can use the solutions that others have mentioned and use any of the following in a sensible way.
double.parse,
double.tryparse
isNumeric()
My personal preference would be for isNumeric() but the choice is really up to you.
You can ignore characters in the textbox's keypress event, like:
Private Sub txtValue_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress
If Not Char.IsDigit(e.KeyChar) Then
If Not (e.KeyChar = vbBack) Then
e.Handled = True
End If
End If
End Sub
not sure which version of VB you're using, assuming it's .NET
You can also use Textbox Keypress event. i.e
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Textbox1.KeyPress
If (e.KeyChar < "0" Or e.KeyChar > "9") And e.KeyChar <> "." And e.KeyChar <> ControlChars.Back Then
e.Handled = True
Else
If e.KeyChar = "." Then
If Textbox1.Text.Contains(".") Then
Beep()
e.Handled = True
End If
End If
End If
End Sub
I hope this helps.