having trouble working out why this won't check the textbox too as well as the selected color. If I do not put a color it flags up the "please enter fields" message, however if I do select a color but do not put anything in the name textbox then it carries on and just outputs a blank string in the msgbox.
Code is:
Dim newColor As Color
Dim userName As String
Dim notEnoughArguments As String = "Please fill out the fields"
'Click event for button
Private Sub enterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enterBtn.Click
If (userName Is "") Then
MsgBox(notEnoughArguments)
ElseIf (userName Is "" And colorLtb.SelectedItem Is Nothing) Then
MsgBox(notEnoughArguments)
ElseIf (colorLtb.SelectedItem Is Nothing) Then
MsgBox(notEnoughArguments)
Else
userName = txt1.Text
Dim selectedColor As String = colorLtb.SelectedItem.ToString
newColor = Color.FromName(selectedColor)
Dim msgBoxText As String = "Hello " + txt1.Text + "." & vbCrLf + "Changing your color to " + selectedColor + "."
MsgBox(msgBoxText)
Me.BackColor = newColor
End If
End Sub
For strings (like your textbox contents) use String.IsNullOrWhitespace as a test. Also you want both arguments, right? So a single statement should do:
If String.IsNullOrEmpty(userName) OrElse colorLtb.SelectedItem Is Nothing Then
MessageBox.Show(notEnoughArguments)
Return
End If
The problem is that Dim userName As String means the variable has nothing at all and that is not the same as an empty string. I always declare strings and immediately set them to String.Empty to avoid null reference exceptions, but using String.IsNullOrEmpty is a clean and robust way to test the contents of a string variable.
Normally to test for equality in VB, you use a single = rather than Is
If (userName = "") Then
When testing for Nothing, you have to use Is
If (userName Is Nothing) Then
IsNullOrEmpty combines both tests. As the accepted answer suggests:
If (String.IsNullOrEmpty(userName)) Then
Related
I'm a newbie in VB.NET so I followed a tutorial. The current code only takes the first value, operator, and then the second value before I press the equal button. It's working as intended. But I want to know how to make it accept multiple values and multiple operators before I press the Equal button.
Here is the current code for the operator buttons and the equal button and the variables declared:
Dim firstval, secondval, result As Double
Dim op As String
Private Sub Operator_Click(sender As Object, e As EventArgs) Handles Button17.Click, Button16.Click, Button15.Click, Button14.Click
Dim b As Button = sender
firstval = Label1.Text
Label2.Text = Label1.Text
Label1.Text = ""
op = b.Text
Label2.Text = Label2.Text + " " + op
End Sub
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
secondval = Label1.Text
If op = "+" Then
result = firstval + secondval
Label1.Text = result
ElseIf op = "-" Then
result = firstval - secondval
Label1.Text = result
ElseIf op = "×" Then
result = firstval * secondval
Label1.Text = result
ElseIf op = "÷" Then
result = firstval / secondval
Label1.Text = result
If secondval = "0" Then
Label1.Text = ""
Label3.Text = "CANNOT DIVIDE BY ZERO"
End If
End If
End Sub
You could use a string to store the entire math problem the user inputs and add the number or operator to it depending on the button you click. This way you could have practically infinite amounts operators and numbers.
When the string is done you can let it calculate when the "=" button or whatever button you're using is pressed.
You would start by declaring the variable
Dim input As String
Then use this code when you click a button
input = input + NAMEOFBUTTON.text
This will make it add the content of the button to the current input. NAMEOFBUTTON would be the name of the button the code runs under.
You might need to use "/" as the button name for division.
When clicking on "=" this code should run:
Dim output = New DataTable().Compute(input, Nothing)
Then you could use a label to display the output. NAMEOFLABEL is of course the name of the label you display it on.
You might need to convert the output to a string before showing it on a label.
NAMEOFLABEL.text = output.ToString
I have a form in where users need to input integers to save to an xml when they press a button
the issue lies that when the user does not put in valid input, it displays the error but still attempts to declare the variables for my function and then crashes - how do i stop this?
here's my code:
If IsNumeric(txtLevel.Text) And IsNumeric(txtHealth.Text) Then
MsgBox("choose a location to save in")
ElseIf String.IsNullOrWhiteSpace(txtHealth.Text) Or String.IsNullOrWhiteSpace(txtLevel.Text) Then
MsgBox("you have not filled in all fields")
Me.Close()
Else MsgBox("please input number form")
End If
Dim strName As String = txtCharacter.Text
Dim intLevel As Integer = txtLevel.Text
Dim intHealth As Integer = txtHealth.Text
Dim strStat As String = cmbStat.Text
You are using quite a few legacy features and you also have Option Strict turned off.
IsNumeric should be replaced with Integer.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse
MsgBox should be replaced with MessageBox: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.messagebox
For more information on option strict, I suggest you check out any of these resources:
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-strict-statement
https://www.vblessons.com/lessons.html#/1/2
http://vb.net-informations.com/language/vb.net_option_strict.htm
With that being said, your code could look like this:
Dim strName As String = txtCharacter.Text
Dim strStat As String = cmbStat.Text
Dim intLevel, intHealth As Integer
' if either condition is true, close the form prematurely
If (String.IsNullOrWhitespace(txtLevel.Text) OrElse String.IsNullOrWhitespace(txtHealth.Text)) Then
MessageBox.Show("You have not filled in all fields.", "Invalid Form")
Me.Close()
ElseIf (Not Integer.TryParse(txtLevel.Text, intLevel) OrElse Not Integer.TryParse(txtHealth.Text, intHealth)) Then
MessageBox.Show("Please input number form.", "Invalid Form")
Me.Close()
End If
' continue on with the code
Move your variable declaration inside your "If IsNumeric(txtLevel.Text) And IsNumeric(txtHealth.Text) Then" so its only going to try to assign them the value if both txtLevel and txtHealth are integers.
I would suggest you to change the code like so:
'Checks if the textboxes are not empty
If Not String.IsNullOrWhiteSpace(txtHealth.Text) Or String.IsNullOrWhiteSpace(txtLevel.Text) Then
'They are not empty, so the program checks if they are integers
If IsNumeric(txtLevel.Text) And IsNumeric(txtHealth.Text) Then
'The input is integer
Dim strName As String = txtCharacter.Text
Dim intLevel As Integer = txtLevel.Text
Dim intHealth As Integer = txtHealth.Text
Dim strStat As String = cmbStat.Text
MsgBox("choose a location to save in")
Else
'The input is not integer
MsgBox("Value is not an integer")
End If
Else
'A textbox is empty
MsgBox("you have not filled in all fields")
Me.Close()
End If
you can try with TryParse to be sure of integer value without error :
Dim intLevel As Integer
Dim intHealth As Integer
If (Integer.TryParse(txtLevel.Text, intLevel)) And (Integer.TryParse(txtHealth.Text, intHealth)) Then
MsgBox("choose a location to save in")
ElseIf String.IsNullOrWhiteSpace(txtHealth.Text) Or String.IsNullOrWhiteSpace(txtLevel.Text) Then
MsgBox("you have not filled in all fields")
Me.Close()
Else MsgBox("please input number form")
End If
Dim strName As String = txtCharacter.Text
Dim strStat As String = cmbStat.Text
find more about it on : Int32.TryParse Method
I'm working on a project that displays text on a monitor as a reference but running into some logic trouble. Someone clicks a button which prompts an InputBox into which they insert a bar code with a scanner.
I have 2 types of part numbers, one is like this "11n11110mch" the other is something like this "12311110mch". I need code that tests whether the 3rd character is a number. The end goal is to display the number as "11.(some letter)111.10 MCH" and "123.111.10 MCH" in a TextBox. If I try "11n22210mch", I get an error that says
Conversion from string "n" to type 'Double' is not valid.
at
thirdChara = Mid$(VisPartID, 3, 1)
I am not sure how to correct this or accomplish what I am trying to do.
The code I have:
Public Sub btnScan_Click(sender As Object, e As EventArgs) Handles btnScan.Click
Dim ScanIDRaw As Object
'Clear Scan Value
ScanIDRaw = Nothing
'Display message, title, And default value.
ScanIDRaw = InputBox("Scan CDI", "InputBox")
Do Until ScanIDRaw IsNot ""
ScanIDRaw = InputBox("Part Number Needed, Scan CDI", "InputBox")
Loop
lblCDIPart.Text = ScanIDRaw
HUD.ReferenceCardDataPull()
End Sub
Public Async Sub ReferenceCardDataPull()
Dim PartID As String
Dim VisPartID As String
Dim thirdChara As String
'Other Code
'Something
'Something
VisPartID = Main.lblCDIPart.Text
thirdChara = Mid$(VisPartID, 3, 1)
If thirdChara = Not IsNumeric(thirdChara) Then
VisPartID = VisPartID.Insert(2, ".")
VisPartID = VisPartID.Insert(7, ".")
VisPartID = VisPartID.Insert(10, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
Else
VisPartID = VisPartID.Insert(3, ".")
VisPartID = VisPartID.Insert(8, ".")
VisPartID = VisPartID.Insert(11, " ")
VisPartID = VisPartID.ToUpper
lblPart.Text = VisPartID
End If
End Sub
If Not isNumeric(thirdChara) Then
But you really should be using VB.Net methods instead of the old VB6 style
dim position3 as integer
thirdChara = VisPartID.SubString(2,1) ' 2 because we're 0 based
if not integer.tryparse(thirdChara, position3) then
'do stuff if not a number
else
'it's a number
end if
The tryparse will return a boolean based upon the parse result. Upon successful parse, it will store the parsed value into the variable (in this case Position3)
I would also recommend turning on Option Strict as that would have informed you right away that you cannot implicitly convert a string to a boolean.
Meaning: The string thirdChara is being tested for equality against as Not (True|False) result from the IsNumeric method.
How can I add tOGGLE cASE to textboxes, for example, I click a button and it changes the text in a textbox to tOGGLE cASE (hello -> hELLO), basically it takes first letter and lower cases it and the rest upper cases it.
Here is a method using .NET Culture functions to first convert to Title Case and then invert the case to your "tOGGLE cASE"
Private Sub btn_ConvertTotOGGLEcASE_Click(sender As Object, e As EventArgs) Handles btn_ConvertTotOGGLEcASE.Click
'Get the current value of the textbox
Dim MyText As String = MyTextBox.Text
'Convert it to Title Case using built in .NET tools
Dim MyTextInfo As System.Globalization.TextInfo = New System.Globalization.CultureInfo("en-US", False).TextInfo
MyText = MyTextInfo.ToTitleCase(MyText)
'Then invert the case of all the characters
Dim InvertedText As Char() = MyText.Select(Function(c) If(Char.IsLetter(c), If(Char.IsUpper(c), Char.ToLower(c), Char.ToUpper(c)), c)).ToArray()
'Finally convert it back to a string
MyTextBox.Text = New String(InvertedText)
End Sub
You can split you string in an array, iterate in the array with lcase(mid(string,1,1) & ucase(mid(string,2, len(string)-1)), and recompose your array in a string
Public function ToogleText(myStr as string) as string
dim str() as string
str = split(myStr," ")
dim toogleStr as string
toogleStr = ""
for each substr as string in str
toogleStr = toogleStr & lcase(mid(substr,1,1)) & ucase(mid(substr, 2,len(substr)-1)) & " "
next substr
if len(toogleStr) > 0 then
ToogleText = mid(toogleStr,1,len(toogleStr)-1)
else
ToogleText =""
end if
end function
I'm trying to use this script to compare a users input from a text box with the 22 correct words. I'm not looking for multiple cases, such as VICE is in ADVICE so it would be 2 values; I want it to have the string values to accept only equal values.
At the moment, it is only recognizing the first word TIED and displays a message box "found", but it doesn't not recognize any other word in the list.
I am writing in visual basic script
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
Dim Find As String = userinput
For Each Str As String In StrCorrect
If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
MsgBox("Found" & userinput)
Return
Else : MsgBox("incorrect word")
Return
End If
Next
End Sub
The problem is that your loop is explicitly returning if the first item isn't a match. You only know you don't have a match if your loop completes without finding one, so try something like this instead:
For Each Str As String In StrCorrect
If StrComp(Str, userinput, CompareMethod.Text).ToString = 0 Then
MsgBox("Found" & userinput)
Return
End If
Next
MsgBox("incorrect word")
This will only display "incorrect word" if all of the items in your list fail the first test.
Why STRCOMP? Why not a direct comparision if you want an exact match?
For Each Str As String In StrCorrect
If Str = Find Then
MessageBox.Show("Found :" & Str)
End If
Next
Try like below, It will help you...
Sample :
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
MsgBox("Found : " & userinput)
Else
MsgBox("incorrect word")
End If
Full Code :
Dim StrCorrect() As String = {"TIED", "VICE", "ICED", "DIVE", "DIET", "DATE", "CITE", "CAVE", "AIDE", "ACED", "CITED", "ACTED", "VACATE", "CATTIE", "ADVICE", "AVIATE", "ACTIVE", "VACATED", "DICTATE", "AVIATED", "ACTIVATE", "ACTIVATED"}
Dim Find As String = userinput
Dim result As String() = Array.FindAll(StrCorrect, Function(s) s.Equals(Find))
If (result.Length > 0) Then
MsgBox("Found : " & userinput)
Else
MsgBox("incorrect word")
End If
I would use a for loop, something like
For i As Integer = 0 To StrCorrect.Length - 1
If StrCorrect(i) = Find Then
MsgBox("Found" & Find)
Return
'End if
'The else statement simply alerting that it didnt find the right word on this iteration
'The else can be removed if you dont want this alert
Else
MsgBox("incorrect word")
'Return
End If
Next