VB TextBox entry handling - TAB key missing - vb.net

Windows 10/VS 2015 Community/Visual Basic 2014
I have written the following to input text from 13 TextBoxes. It inputs
each character with its own event. Each character is checked for being
a valid character (numerals, letters, symbols) plus Cr (to move to next
TextBox) and BS (to permit typo corrections). This works:
'===== Enter Frequency =====
Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
ichar = e.KeyChar()
ckinchar() 'ck for input characters, or CR or BS keys
If eoline = 1 Then 'has <cr> been detected?
freq = inline 'Yes
bufcnt = 0 'Reset counter
eoline = 0 'Rest EOL flag
TextBox1.BackColor = Color.LightGreen
TextBox2.BackColor = Color.LightPink
TextBox2.Focus()
Exit Sub
Else
TextBox1.Focus() 'No - repeat inputting
End If
End Sub
Problem: I wish to also use the TAB key (to be implemented as the Cr key)
However the TAB key code fails to appear. In run mode pressing the Tab key
causes the cursor to move up the displayed TextBoxs following the tabIndex order. I've tried using KeyDown/Enter/TextChanged events to no effect -
mostly problems getting implemented.
Can anyone suggest any errors I might have in first two lines, or alternative choice. Is/are there any Properties in the TextBox I should be looking at.
TIA Day Watson

Private Sub TextBox1_PreviewKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.PreviewKeyDownEventArgs) Handles TextBox1.PreviewKeyDown
If e.KeyCode = Keys.Tab Then
Me.Text = "TAB Captured"
End If
End Sub

Related

How to force text being entered into a textbox into Uppercase?

I want to make the text that a user is typing into a textbox become uppercase. I know two ways to do this, which are:
Textbox1.Text = UCase(Textbox1.Text)
or
Textbox1.Text = Textbox1.Text.ToUpper
HOWEVER: both have the same problem (when embedded in a Textbox1_TextChanged event handler), which is that the cursor keeps being moved back to the start, so if you slowly type in, say abcdef, it comes out as FEDCBA. Is there a way to move the cursor back to the end of the string after each time it works to make the text uppercase?
go to textbox property, change CharacterCasing to Upper
Use the KeyPress event to detect lower case letters being entered, and convert them to uppercase as you go:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii > 96 And KeyAscii < 123 Then
'Typed letter from "a-z", map it to "A-Z"
KeyAscii = KeyAscii - 32
End If
End Sub
Ucase() is used only after the person is done entering the text.
If you are using VB.NET then you just need to set the .CharacterCasing property of the TextBox to .Upper - No code needed. But if you wanted to use code for some reason, use this:
TextBox1.CharacterCasing = CharacterCasing.Upper
Why don't you just place the code Textbox1.Text = Textbox1.Text.ToUpper in the Textbox1_LostFocus event instead of the Textbox1_TextChanged event. It's so simple and it works even if you paste text into the field. As soon as your cursor moves to another field, the event is triggered, causing the text to change case from lower to upper.
You could also use:
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Textbox1.KeyPress
e.KeyChar = UCase(e.KeyChar)
End Sub
... if you need to do some custom formatting or logic. Otherwise I'd also suggest using the default TextBox property CharacterCasing set to Upper.
Please note that this solution does not handle the situation when user is pasting text into the TextBox component and you have to programmatically take care of that situation too if needed, but the TextBox property CharacterCasing does it for you even if user is pasting text into the component.
Your version didn't quite work for me in Visual Basic 2019, but it formed the basis of this, which does (where "txtPrem1" is the TextBox):
Private Sub txtPrem1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtPrem1.KeyPress
Dim KeyAscii = AscW(e.KeyChar)
If KeyAscii > 96 And KeyAscii < 123 Then
'Typed letter from "a-z", map it to "A-Z"
KeyAscii = KeyAscii - 32
End If
e.KeyChar = ChrW(KeyAscii)
End Sub
How about this:
Private Sub MyText_TextChanged(sender As Object, e As EventArgs) _
Handles MyText.TextChanged
Dim oText As TextBox = CType(sender, TextBox)
oText.Text = oText.Text.ToUpper
oText.SelectionStart = oText.Text.Length
oText.SelectionLength = 0
End Sub

How can I make it so a TextBox will dynamically adjust the input as a currency format?

This app I'm designing has a TextBox named txtValue with the properties MaxLength set to 14 and TextAlign set to Right. I want txtValue to only accept currency, and dynamically format the input so the user doesn't need to add commas, only one period.
I managed to make it so txtValue will only accept numbers and one dot in the event txtValue_KeyPress.
txtValue_LostFocus will convert the input into currency format.
Here's my code so far:
Private Sub txtValue_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtValue.KeyPress
'Allows only one dot
If (e.KeyChar.ToString = ".") And (txtValue.Text.Contains(e.KeyChar.ToString)) Then
e.Handled = True
Exit Sub
End If
'Allows only 0 to 9 and dot (once)
If (e.KeyChar.ToString < "0" OrElse e.KeyChar.ToString > "9") _
AndAlso e.KeyChar <> ControlChars.Back _
AndAlso e.KeyChar.ToString <> "." Then
e.Handled = True
End If
End Sub
Private Sub txtValue_LostFocus(sender As Object, e As EventArgs) Handles txtValue.LostFocus
txtValue.Text = Format(Val(txtValue.Text), "000,000,000.00")
End Sub
I expect the input -q1w23456789012....34 to return the output 123,456,789,012.34, but the actual output after it loses focus is 123,456,789,012.30
This seems like an easy fix, like setting MaxLength to 15, but then if I don't type a period, it'll allow me to type 15 numbers and I only want up to 12 plus 2 after the period.
I expect the input -q1w234....5678 to return the output 1,234.56, but the actual output after it loses focus is 000,000,001,234.56
This seems like a more complex fix, because I don't want to use the LostFocus event to validate what I type. I want the KeyPress event to handle the input and dynamically format what I type.
In this case:
The input 1 would have the output 1.00
The input 123.4 would have the output 123.40
The input 1234.567 would have the output 1,234.56
All of this without needing the LostFocus event, but right now I'm using the LostFocus event because that's all my very limited knowledge allows me to do.
UPDATE
Alright I'm now using the Leave event, but then again I was only using LostFocus as a placeholder because in the end I want the TextBox to adjust what the user types as they type.
An alternative way to handle. For details on formating numbers for display try MS docs https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings or https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
Private err As New ErrorProvider()
Private d As Decimal 'In case you want to use the value as a number somewhere else
Private Sub TextBox17_Validating(sender As Object, e As CancelEventArgs) Handles TextBox17.Validating
If Not Decimal.TryParse(TextBox17.Text, d) Then
e.Cancel = True
err.SetError(TextBox17, "This text box must contain a number.")
Else
err.Clear()
End If
End Sub
Private Sub TextBox17_Validated(sender As Object, e As EventArgs) Handles TextBox17.Validated
TextBox17.Text = d.ToString("C")
End Sub

Barcode scanning to a listbox checking for duplicates

Good day!
I want to add some strings from a barcode scanner, captured in a text box, to a list box, and, before adding it, to check if the specific string hasn't been already added. So I have a text box called txtWO which captures what the reader scans and a list box called lstScanBOM to which I add the text box string if the item is not already added. The problem is, that whatever I do, only after the specific string is added twice the checking for duplicate entry starts to work. In other words I scan the same string twice, it added it, and then when I scan the third time only it throws the message with the error saying it is a duplicate. I don't understand why is doing this. The code is below:
Private Sub frmValidareFIP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If txtWO.Focused = False Then
txtWO.Select()
End If
End Sub
Private Sub AddUnique(StringToAdd As String)
If lstScanBom.Items.Contains(StringToAdd) = True Then
MsgBox("Articol duplicat!", vbOKOnly)
Else
'it does not exist, so add it..
lstScanBom.Items.Add(StringToAdd)
End If
End Sub
Private Sub txtWO_KeyDown(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWO.KeyDown
If e.KeyCode = Keys.Enter Then
Dim barcode As String
barcode = txtWO.Text
AddUnique(barcode)
txtWO.Clear()
txtWO.Focus()
End If
End Sub
IMO Try listing the data outside of the ListBox. I can't see why it isn't working, maybe we need a third pair of eyes to see it!?
Try adding a list (of string) as a Private within the form, populate this as your user scans, and check the duplicate there..
This is definately not the best solution, but I'm sure it will help!
Private List_Barcodes As List(Of String)
Private Sub frmValidareFIP_Load(sender As Object, e As EventArgs) Handles MyBase.Load
List_Barcodes = New List(Of String)
'You can also populate this list on load, if you have a stored cahce of previous scanned barcodes?
'List_Barcodes.Add("0123456")
'List_Barcodes.Add("4567890")
'...etc
If txtWO.Focused = False Then
txtWO.Select()
End If
End Sub
Private Sub AddUnique(StringToAdd As String)
If List_Barcodes.Contains(StringToAdd) Then
MsgBox("Articol duplicat!", vbOKOnly)
Else
'Place into dynamic list
List_Barcodes.Add(StringToAdd)
'and Place into your listbox
lstScanBom.Items.Add(StringToAdd)
End If
End Sub
Private Sub txtWO_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWO.KeyDown
If e.KeyCode = Keys.Enter Then
Dim barcode As String
barcode = txtWO.Text
AddUnique(barcode)
txtWO.Clear()
txtWO.Focus()
End If
End Sub
Your barcode reader is returning <carriage return><line feed> as enter. Your code catches the enter key (carriage return = 13), but leaves the line feed (10) character. So the next time you scan something it will start with a line feed. The two strings in your example are different because the first is "58335001" and the second is "<line feed>58335001". The third one is "<line feed>58335001", which is a duplicate of the second.
One way to fix this is to trim your string.
Private Sub txtWO_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtWO.KeyDown
If e.KeyCode = Keys.Enter Then
Dim barcode As String
'Add the .Trim() to remove the leading <line feed> character
barcode = txtWO.Text.Trim()
AddUnique(barcode)
txtWO.Clear()
txtWO.Focus()
End If
End Sub
The most simple decision is ONLY to make your textBox control txtWO NOT multiline
And that's enough! Your code will work correctly!

Validating textbox when enter button is pushed

I'm creating a AddIn for Autodesk Inventor (3D drawing software), and for the moment I am playing with positional constraints.
I created a custom user menu for quick editing certain values, in this case the elevation and orientation value.
First I used the textbox.textchanged event to change my constraint value. But this was working not 100%. Example when pressing elevation 1000 would change the elevation 4 times ( on per digit ).
Now I went to using the validated event. This works better, BUT I would like to have the textbox to initiate validation when the Enter button is pressed. For this I whipped up this, but it's not correct i'm sure of it. How should I write this correctly?
The code below works but, I would like to have a proper way to achieve the result.
Private Sub tbElevationValue_TextChanged(sender As Object, e As EventArgs) _
Handles tbElevation.Validated
' If the elevation parameter and textbox value are the same
' The sub must be aborted
If CDbl(tbElevation.Text) = oElevationParameter.Value * 10 Then Exit Sub
' Check the entered value
Dim oValue As Double
If tbElevation.Text = "" Then
oValue = 0
tbElevation.Text = 0
Else
oValue = tbElevation.Text
End If
' Set the parameter value
oElevationParameter.Value = oValue / 10
' Update the document
EM_AddIn.StandardAddInServer.m_inventorApplication.ActiveDocument.Update()
End Sub
Private Sub tbOrientation_TextChanged(sender As Object, e As EventArgs) _
Handles tbOrientation.Validated
' If the orientation parameter and textbox value are the same
' The sub must be aborted
If CDbl(tbOrientation.Text) = cRandiansToDegrees(oOrientationParameter.Value) Then Exit Sub
' Check the entered value
Dim oValue As Double
If tbOrientation.Text = "" Then
oValue = 0
tbOrientation.Text = 0
Else
oValue = tbOrientation.Text
End If
' Set the parameter value
oOrientationParameter.Value = cDegreesToRandians(oValue)
' Update the document
EM_AddIn.StandardAddInServer.m_inventorApplication.ActiveDocument.Update()
End Sub
Private Sub OrientationElevationEnterKey_Pressed(sender As Object, e As Windows.Forms.KeyEventArgs) Handles tbElevation.KeyUp, tbOrientation.KeyUp
If e.KeyCode = Windows.Forms.Keys.Enter Then
CType(sender, Windows.Forms.TextBox).Parent.Focus()
CType(sender, Windows.Forms.TextBox).Focus()
End If
End Sub
I think you're on the right way. It can be a pain to register a key_down event for each TextBox object, but your idea is good.
You can set a key_down event listener to your form instead.
Try something like this:
Private Sub Main_KeyDown(sender As Object, e As KeyEventArgs) Handles MyBase.KeyDown
If e.KeyCode = Keys.KeyCode.Enter Then
MyBase.Focus() ' this will cause the currently focused control to validate
End If
End Sub

How to prevent special characters in datagridview using vb.net

I have a windows forms vb.net program that uses a datagridview. I'm trying to find a way to prevent a user from entering special characters (e.g. $,#,!,#,%,^,&) in my datagridview. When the user inputs a special character I have an approprioate message box appear explaining their mistake, then I provide them a default value. I have everything working except a way to prevent the special character or symbols. I'm thinking something like this has to work, but I can't seem to find any way of preventing this sort of entry:
If (columnindex = 0) Then 'checking value for column 1 only
Dim cellString = DataGridView1.Rows(rowindex).Cells(columnindex).value
If cellString String.IsSymbol(cellString) = true Then
MessageBox.Show("Special Characters Not Allowed")
End If
DataGridView1.Rows(rowindex).Cells(columnindex).value = "Default Value"
Exit Sub
End If
You can use the EditingControlShowing event to register a KeyPress function for the input box.
Private Sub YourDataGridView_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles YourDataGridView.EditingControlShowing
Try
RemoveHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
Catch ex As Exception
End Try
If Me.dgvTableViewer.CurrentCell.ColumnIndex = YourDataGridView.Columns("YourColumn").Index Then
AddHandler e.Control.KeyPress, AddressOf YourFunctionToPreventSpecialCharacters
End If
End Sub
Try and Put this in the DataGridView's keydown event:
Private Sub DataGridView1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles DataGridView1.KeyDown
Select Case e.KeyCode
Case Keys.D0 To Keys.D9 And e.Shift
MsgBox("NOPE.")
e.SuppressKeyPress = True
End Select
End Sub
That basically checks if the keypress is coming from the 0-9 keys on your computer and also if you are holding the SHIFT Key. If it is then it displays a Msgbox and Suppresses the keypress. This blocks chars on your keyboard's 0-9 shift !##$%^&*(). You can edit this like
Case Keys.A
e.Suppress ...
Msgbox ... etc