VB Text Box accepting Non numeric Data - vb.net

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

Related

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.

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

VBA Find function incorrect highlighting

Can somebody help me fix this code, I have two textbox where when you paste the text on the 1st Textbox and click the search button, it highlighted the exact text on the 2nd textbox if it is present on the 2nd textbox. But when the string on 2nd textbox contains linefeed/newline, it added one character from the start of the text. Here is the code:
Private Sub FindText(ByVal start_at As Integer)
Dim pos As Integer
Dim target As String
target = Textbox1.Text
pos = InStr(start_at, Textbox2.Text, target)
If pos > 0 Then
' We found it.
TargetPosition = pos
Textbox2.SelStart = TargetPosition - 1
Textbox2.SelLength = Len(target)
Textbox2.SetFocus
Else
' We did not find it.
MsgBox "Not found."
Textbox2.SetFocus
End If
End Sub
' Search button
Private Sub cmdSearch_Click()
FindText 1
End Sub
I believe the problem is that Textbox is treating newline as a single character while Len() counts as CRLF as two. You should probably count the number of times CRLF appears in the text preceding the match target and adjust SelStart accordingly. Try this line instead:
Textbox2.SelStart = Len(Replace(Left(target, pos - 1), vbCrLf, "^")) - 1
'Textbox2.SelLength = Len(Replace(target, vbCrLf, "^"))
If target can include line breaks you may have a similar problem with SelLength which is why I've left the second, commented line. This works by substituting two-character line-break sequences into a single-character string. It's completely arbitrary what value to use for replacement since the result is discarded and only the length ultimately matters.

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

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

Is possible to ignore the TextBox?

I'm creating a program to calculate the average. There are 12 TextBox and I want to create the possibility to leave some fields blank. Now there are only errors and the crash of the program. Is possible to create that?
This is part of code:
ItalianoScritto = (TextBox1.Text)
MatematicaScritto = (TextBox2.Text)
IngleseScritto = (TextBox3.Text)
InformaticaScritto = (TextBox4.Text)
ScienzeScritto = (TextBox5.Text)
FisicaScritto = (TextBox6.Text)
MediaScritto = (ItalianoScritto + MatematicaScritto + IngleseScritto + InformaticaScritto + ScienzeScritto + FisicaScritto) / 6
Label10.Text = Str(MediaScritto)
If i leave blank the textbox1 when I click on the button to calculate the average Vb says Cast not valid from the string "" to type 'Single' and the bar of te textbox1 become yellow
I would do the following:
Iterate over the textboxes and check if you can parse the value into an iteger. If yes, add it to a value list.
Then add all values from that list and divide it by the number of cases.
It is faster than big if-statements and resilient against error
dim TBList as new list(of Textbox)
'add your textboxes to the list here
TbList.add(Textbox1)
...
dim ValList as new List(Of Integer)
for each elem in Tblist
dim value as integer
If integer.tryparse(elem.text,value)=True
ValList.add(Value)
else
'report error or do nothing
end if
next
dim Result as Integer
Dim MaxVal as Integer =0
for each elem in ValList
Maxval +=elem
next
Result = MaxVal / ValList.count
If you need support for point values, just choose double or single instead of Integer.
Also: regardless what you do -CHECK if the values in the textboxes are numbers or not. If you omit the tryparse, somebody will enter "A" and your app will crash and burn
Also: You OPTION STRICT ON!
You just have to check if the TextBox is blank on each one before using the value:
If TextBox7.TextLength <> 0 Then
'Use the value inside
End If
The way to do it depends a lot of your code. You should consider editing your question giving more information (and code) in order to us to help you better.