How do I filter and substitue TextBox characters during input in VB.net 2005 - vb.net

I have two textBox input fields that must be numeric only, limited to 7 digits. However, the target device has a tiny keyboard with a shared numeric keypad that is accessible via a numlock key, so the key 'E' doubles as the '1'. The problem is that with the numlock enabled the backspace/del key does not work so input is difficult... fat fingers constantly pushing the wrong key, etc...
So what I would like to do is automatically convert 'E' to '1', 'R' to '2', etc, as I type. I don't want to see 'E' then '1', it has to look just like the numlock is pressed. It also has to accept 0..9 if the numlock is pressed.
Substitute these characters: "ertdfgxcvERTDFGXCV0123456789"
for these: "012345678901234567890123456789"
Is there an easy way to do this in VB.net-2005 ?

You can use this event;
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim counter As Integer = 0
For Each c As Char In "ertdfgxcvERTDFGXCV"
If e.KeyChar = c Then
e.KeyChar = Chr(48 + counter)
End If
counter += 1
If counter = 10 Then counter = 0
Next
End Sub

Related

VB windows form calculate the digit in a multiline textbox

I want to calculate each line: it's like first line 123*1.616 and the second line 213*1.616, and display each total.
Every number entred in the kilogram textbox will mutiply 1.616 and then show the result in the kati label.
Here is my code:
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Enter
For Each digit In (TextBox1.Text)
total1 = Val(digit) * 1.616
Label9.Text = total1
Next
Label9.Text = total1
End sub
Please help me find some solution or explanation to achieve the output.
This should work
Private FACTOR As Decimal = 1.616
Private SEPARATOR As String = Environment.NewLine
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
Label9.Text = TextBox1.Text.
Split({SEPARATOR}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(s1) $"{Decimal.Parse(s1) * FACTOR:0.00#}").
Aggregate(Function(s1, s2) $"{s1}{SEPARATOR}{s2}")
End Sub
Here are the functions in the LINQ
Split makes an array out of each line in the TextBox using SEPARATOR as the delimiter
Select transforms the elements into their value times FACTOR
Aggregate puts the elements back together into a SEPERATOR delimited string
Why didn't your original code work?
You were iterating over each char in the text, and multiplying the char by a float (Option Strict On, as suggested in the comments would have prevented that).
Then in each iteration, you do (simplified) Label9.Text = Val(digit) * 1.616 which overwrites the Label every time.
If you were to step through in debug (also suggested in comments), you would see the Label becoming 1x1.616=1.616, 2x1.616=3.232, 3x1.616=4.848, etc. The result was the very last character in your TextBox, '3', times 1.161 = 4.848. Obviously, this was not what you wanted. You needed to instead iterate over each entire number. The multiline TextBox separates each line with a new line. So we iterate over each line instead.
you can use split string by vbCrLf
Sub main()
Dim multilinetext As String =
"10
20
30
40
50
60"
Dim number_array = multilinetext.Split(vbCrLf)
Dim output As Integer = 0
For Each i In number_array
output += i
Next
Stop
End Sub

Invalid Cast Expectation Was Unhanded (when checking the contents of a text box)

This code is from a subroutine that checks if a text box entry fits the criteria specified (an integer between 1 and 100).
The first IF statement should check if it is not a numerical entry. If it is not numerical then the contents of the text box should be set blank so that a number can be entered.
The second IF statement should check if the number is larger than 100. If it is then the contents of the text box should be set blank so that an appropriate number can be entered.
The Third IF statement should check if the number is smaller than 1. If it is then the contents of the text box should be set blank so that an appropriate number can be entered.
Finally the contents of the box should be set as the variable.
I initially programmed the first IF statement on its own and it worked. But upon adding the others my program would crash when I typed anything into the text box and the error was as stated in my title. I have looked at multiple solutions and have found nothing for almost 2 days that fixed the problem.
Any suggestions would be appreciated.
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles NumQTextBoxInput.TextChanged
'Check if input is numeric
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = ""
If (NumQTextBoxInput.Text > 100) Then
NumQTextBoxInput.Text = ""
End If
If (NumQTextBoxInput.Text < 1) Then
NumQTextBoxInput.Text = ""
End If
ArchwayComputingExamCreator.GlobalVariables.NumOfQuestions = NumQTextBoxInput.Text
'Setting the variable to the contense
End Sub
You should always use the appropriate parse function when accepting text for numbers.
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles NumQTextBoxInput.TextChanged
Dim Value as integer
If Not Integer.TryParse(NumQTextBoxInput.text, Value) OrElse Value < 1 OrElse Value > 100 Then NumQTextBoxInput.Text = ""
... no idea if the archway bit is really what you wanted so left that out ....
End Sub
In this operation:
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = ""
Any time the input is not numeric, you set it to a value which is still not numeric. So any numeric comparison will fail:
If (NumQTextBoxInput.Text > 100)
Maybe you meant to set the value to some numeric default?:
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = "0"
Or just exit the method entirely when it's not numeric?:
If Not IsNumeric(NumQTextBoxInput.Text) Then
NumQTextBoxInput.Text = ""
Return
End If
Or perhaps something else? However you modify your logic, the point is that you can't perform numeric comparisons on non-numeric strings.

VB Text Box accepting Non numeric Data

I have a text box in VB which is set up to only accept only numeric data, and it works, except in TWO specific cases.
If the user provides a NON NUMERIC CHAR the text box self clears,
However, if the user first provides a number, then provides either '-' or '+'
The text box will accept this as a valid input.
When the user types one more char of ANY TYPE, i.e. number or char
Then the text box 'realises' and will self clear.
I was wondering if this is due to the way VB stores the chars '-' and '+'?
Is the best way around this to just add in the two exceptions, i.e. if '-' or '+' are input then self clear?
Or is there a more elegant solution?
Thank you.
Code:
Private Sub TextBox1_Change()
'Textval used as variable from user input
'Numval becomes textval providing the user input is numerical
Dim textval As String
Dim numval As String
textval = TextBox1.Text
If IsNumeric(textval) Then
numval = textval
Else
TextBox1.Text = CStr(numval)
End If
End Sub
code vb.net :
If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then
' your code here
e.Handled = True
End If
and you can Replace text :
code :
Text = Text.Replace("string", "replace_by_this_string")
If the program requires the user to type only numeric data to the textbox, you should enforce the restriction when the user pressed a key
Use the textbox's KeyDown event:
'Omitting the parameters and Handles keyword
Private Sub textbox_KeyDown()
'Set the keys you would want to allow in this array
Dim allowedkeys As Keys() = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9, Keys.D0, Keys.Back}
For i = 0 To allowedkeys.Length - 1 'Iterate through the allowed keys array
If e.KeyCode = allowedkeys(i) Then 'If the key pressed is present in the array...
Exit Sub 'The check returned a success. Exit and accept the key
End If
Next
e.SuppressKeyPress = True 'Supress all keys that failed the check
End Sub
Don't forget to add more keys that you need! The Space key, the numpad keys, the dot (point) keys?
This way you can remove the check in the Changed event and go directly to numval = textval
Or for those lazy programmers, numval = TextBox1.Text and numval = Val(TextBox1.Text) worked as well

Check if a Range in Datagridview contains an "," if yes change it to ":"

My application contains a Datagridview, the user has the possibility to enter values like: Day, Time, how many hours did he work etc. The problem is that my second application calculates with this data. It has to be in a certain format.
Like time should be "09:15", but i noticed that some users are using "09,15" instead. Can you help me guys, I need a code that can check if a Range in Datagridview contains some " blacklisted char" and if yes, replaces it with the right one.
Thanks for all.
Do not save values as a string.
Validate input string straight in the needed type.
Then validated values pass to the second application.
In this case you don't need "blacklisted chars"
Private Sub DataGridView_CellValidating(sender As Object,
e As DataGridViewCellValidatingEventArgs)
If e.RowIndex < 0 Then Exit sub
Dim dgv As DataGridView = DirectCast(sender, DataGridView)
Dim columnIndexWithInteger As Integer = 2
Dim columnIndexWithDate As Integer = 3
Select Case e.ColumnIndex
Case columnIndexWithInteger
Dim temp As Integer
If Integer.TryParse(e.FormattedValue, temp) = False Then
e.Cancel = True
End If
Case columnIndexWithDate
Dim temp As Date
If Date.TryParse(e.FormattedValue, temp) = False Then
e.Cancel = True
End If
End Select
End Sub
In DataGridView, you have one handle that allows you to check the validity of an edited cell : CellValueValidating. It is called before the user change is taken into account (CellValueChanged event).
You can find example and explanation here :
- https://msdn.microsoft.com/en-us/library/ykdxa0bc(v=vs.110).aspx
- https://msdn.microsoft.com/en-us/library/7ehy30d4(v=vs.110).aspx
You can also have a look at CellValueChanged, CellValueValidated and CellEndEdit events.

VB.NET - How to format text boxes so they divide the text into chunks of n letters?

I have two text boxes, that can only contain capital letters, and a variable where I store an unsigned integer. Let's say for instance 5. How can I make it so that my TextBoxes that contain random text are split into groups of 5 letter?
For example: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Becomes: ABCDE FGHIJ KLMNO PQRST UVWXY Z
I need this to be done in real time in case the text is replaced by the user. I also cannot use multiple text boxes that allow n characters each as the text I'm supposed to format can be indefinitely long.
You can use this approach for every time the Textbox.Text changes:
Private Sub Textbox1_TextChanged(sender As Object, e As EventArgs) Handles Textbox1.TextChanged
Dim sentence As String = Textbox1.Text
Dim pairedChars as Integer = 5
If pairedChars <= sentence.Length Then
'First remove all spaces from the last time
sentence.Replace(" ", "")
'Add spaces at every 5th place in the string
For i = 1 to (sentence.Length) / pairedChars
sentence = sentence.Insert(i * pairedChars + (i - 1), " ")
Next
End If
End Sub