Is there something wrong with my coding? I am still new - vb.net

I try to run this program but an error always appears:
Conversion from the string "LBLBuku" to type' Double 'is not valid.
If LBLBuku.Text >= 5 Or Val(LBLBuku.Text) + Val(TextBox1.Text) > 5 Then
MsgBox("Peminjaman Melebihi")
Else
If lbljudul.Text = "" Or TextBox1.Text = "" Then
MsgBox("Silahkan isi Kode Buku")
Else
DataGridView1.Rows.Add(New String() {TextBox2.Text, lbljudul.Text, LBLPengarang.Text, LBLTahun.Text, TextBox2.Text})
TextBox1.Text = ""
TextBox2.Text = ""
lbljudul.Text = ""
TextBox2.Text = ""
LBLPengarang.Text = ""
LBLTahun.Text = ""
Call rumustotalbuku()
End If
End If

Notice on your code the line
LBLBuku.Text >= 5
The property Text is of type String, you would have to convert the text to an integer type first before you can use ">=".

First I declare a variable to hold the integer value in the Text Box. Integer.TryParse will return true if it can convert the string in the text box to an integer. It will also fill the variable intTB1 with the number.
I am assuming that LBLBuku is a label so the .Text property has been set from code. We can depend on this being a number so all we need to do is the conversion with CInt(). We can use the variable we got from the .TryParse in the Or CInt(LBLBuku.Text) + intTB1 > 5 instead of referring to the text box again.
We don't need to check if TextBox1 is empty because it wouldn't have passed the .TryParse if it was.
Last and probably least, you don't need the Call keyword in most situations.
You do realize that you have added TextBox2 twice to the new DataRow.
Private Sub OPCode()
Dim intTB1 As Integer
If Not Integer.TryParse(TextBox1.Text, intTB1) Then
MessageBox.Show("Please enter a number in TextBox1.")
Return
End If
If CInt(LBLBuku.Text) >= 5 Or CInt(LBLBuku.Text) + intTB1 > 5 Then
MsgBox("Peminjaman Melebihi Maksimal")
Else
If lbljudul.Text = "" Then
MsgBox("Silahkan isi Kode Buku")
Else
DataGridView1.Rows.Add(New String() {TextBox2.Text, lbljudul.Text, LBLPengarang.Text, LBLTahun.Text, TextBox2.Text})
TextBox1.Text = ""
TextBox2.Text = ""
bljudul.Text = ""
TextBox2.Text = ""
LBLPengarang.Text = ""
LBLTahun.Text = ""
rumustotalbuku()
End If
End If
End Sub

Related

How to exit loop with "keyword"

Here's my code:
Dim n As String, upper As String, lower As String
Label2.Text = "EXIT"
Label3.Text = "exit"
upper = Label2.Text
Label2.Text = upper.ToUpper
lower = Label3.Text
Label3.Text = lower.ToLower
Do
Label1.Text = InputBox(" Enter a word. If you would like to quit, type: EXIT in the inputbox")
n = Label1.Text
Label1.Text = n.Length
Label1.Text = Label1.Text & " letters"
Loop Until n = ""
Label1.Visible = False
MsgBox(" Invalid value!")
End
Do
Label1.Text = InputBox(" Enter a word. If you would like to quit, type: EXIT in the inputbox")
n = Label1.Text
Label1.Text = n.Length
Label1.Text = Label1.Text & " letters"
Loop Until upper = Label2.Text
Label1.Visible = False
MsgBox(" You have exited the program!")
End
Do
Label1.Text = InputBox(" Enter a word. If you would like to quit, type: EXIT in the inputbox")
n = Label1.Text
Label1.Text = n.Length
Label1.Text = Label1.Text & " letters"
Loop Until lower = Label3.Text
Label1.Visible = False
MsgBox(" You have exited the program!")
End
The issue I'm having with this program is when I run it and press the cancel button or the X button to exit, it executes correctly with the loop. But with the other 2 loops, when I type in "exit" or "EXIT" in uppercase or lowercase, it just displays how many characters are in the word instead of ending the program.
While the answer is missing, I state that the String "Label3" is not part of the InputBox String defaultValue. The "Label1" Text is used and not changed to be saved to "Label2" or "Label3".
The Do Statement seems to iterate with integer datatypes. An sample is to be found on a page for do loop statements.
The negotiation for retriving examples leads to choose either a character or a number. And until a boolean statement is not recognized redirect text like above
Loop Until n = ""
is the easy part.
A newline for an integer value is not necessary a boolean value. The integer can be a boolean value. If integers are dissected until they can be used for a boolean logic the possibiltiy can be used for iterations.
So a string like Text "Label1" is not an obvious boolean value.
I can not sample the question with an answer that takes the whole process apart, but post a part that exits the loop linking the string to a boolean value.
Public Class Form1
Private myValue As Object
ReadOnly AntiPanel As New Label
Private boolenValueTools As Boolean
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim message, title, defaultValue As String
' Set prompt.
message = " Enter a word. If you would like to quit, type: EXIT in the inputbox"
' Set title.
title = "InputBox Demo"
defaultValue = "1" ' Set default value.
'' Display dialog box at position 100, 100.
'myValue = InputBox(message, title, defaultValue, 100, 100)
'' If user has clicked Cancel, set myValue to defaultValue
'If myValue Is "" Then myValue = defaultValue
' Display message, title, and default value.
Do
myValue = InputBox(message, title, defaultValue)
If myValue = "EXIT" Then boolenValueTools = True
Loop Until boolenValueTools = True
' If user has clicked Cancel, set myValue to defaultValue
If myValue Is "" Then myValue = defaultValue
Me.Controls.Add(AntiPanel)
With AntiPanel
.AutoSize = True
.BackColor = Color.Transparent
.Location = New Point(100, 100)
.Font = New Font("Consolas", 55.75, FontStyle.Regular)
.Text = myValue 'in my case also known as NotNamedInputBoxTextString
End With
End Sub
End Class

Evaluating user input decimal variable to range of 1 to 24 or error

Being new to VB I am trying to wrap my thoughts around validating a user input (in textbox) range of 1 to 24. I know this is probably a simple expression but my mind is on a Java expression rather than Visual Basic.
Private Sub HoursAppUsed_TextChanged(sender As Object, e As TextChangedEventArgs) Handles HoursAppUsed.TextChanged
'must check if string is numeric/integer or not'
Dim hoursEntered As String = HoursAppUsed.Text
'And hoursEntered > 0 Or hoursEntered < 25 ???? '
If IsNumeric(hoursEntered) Then
Dim decFromString1 As Decimal = Decimal.Parse(hoursEntered)
hoursEntered = "Value: " + hoursEntered
LabelFour.Content = hoursEntered
Else
LabelFour.Content = "Value is not Numeric!"
End If
'hoursEntered = "Hours Entered: " + hoursEntered'
'LabelFour.Content = hoursEntered'
End Sub
This could be easily achieved with a NumericUpDown-control by setting the Minimum and Maximum properties.
If you still want to use the TextBox instead, following should work:
Dim hoursEntered As String
Dim decFromString1 As Decimal
If Decimal.TryParse(hoursEntered, decFromString1) AndAlso
decFromString1 >= 1 AndAlso
decFromString1 <= 24 Then
hoursEntered = "Value: " + hoursEntered
LabelFour.Content = hoursEntered
Else
LabelFour.Content = "Value is not Numeric!"
End If

If third character Not IsNumeric

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.

What is causing 'Index was outside the bounds of the array' error?

What is causing 'Index was outside the bounds of the array' error? It can't be my file, defianetly not. Below is my code:
Sub pupiltest()
Dim exitt As String = Console.ReadLine
Do
If IsNumeric(exitt) Then
Exit Do
Else
'error message
End If
Loop
Select Case exitt
Case 1
Case 2
Case 3
End Select
Do
If exitt = 1 Then
pupilmenu()
ElseIf exitt = 3 Then
Exit Do
End If
Loop
Dim score As Integer
Dim word As String
Dim totalscore As Integer = 0
'If DatePart(DateInterval.Weekday, Today) = 5 Then
'Else
' Console.WriteLine("You are only allowed to take the test on Friday unless you missed it")
' pupiltest()
'End If
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Dim stdntfname As String = founditem(3)
Dim stdntsname As String = founditem(4)
Dim stdntyear As String = founditem(5)
Console.Clear()
If founditem IsNot Nothing Then
Do
If stdntyear = founditem(5) And daytoday = founditem(6) Then
Exit Do
ElseIf daytoday <> founditem(6) Then
Console.WriteLine("Sorry you are not allowed to do this test today. Test available on " & item(6).Substring(0, 3) & "/" & item(6).Substring(3, 6) & "/" & item(6).Substring(6, 9))
Threading.Thread.Sleep(2500)
pupiltest()
ElseIf stdntyear <> founditem(5) Then
Console.WriteLine("Year not found, please contact the system analysts")
Threading.Thread.Sleep(2500)
pupiltest()
End If
Loop
End If
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\testtests.csv")
Dim item() As String = line.Split(","c)
Dim mine As String = String.Join(",", item(2), item(3), item(4), item(5), item(6))
For i As Integer = 1 To 10
Console.WriteLine(i.ToString & "." & item(1))
Console.Write("Please enter the word: ")
word = Console.ReadLine
If word = Nothing Or word <> item(0) Then
score += 0
ElseIf word = item(0) Then
score += 2
ElseIf word = mine Then
score += 1
End If
Next
If score > 15 Then
Console.WriteLine("Well done! Your score is" & score & "/20")
ElseIf score > 10 Then
Console.WriteLine("Your score is" & score & "/20")
ElseIf score Then
End If
Next
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdntscores", True)
sw.Write(stdntfname, stdntsname, stdntyear, score, daytoday, item(7))
Try
Catch ex As Exception
MsgBox("Error accessing designated file")
End Try
End Using
End
End Sub
All help is highly appreciated,
You are constantly replacing the foundItem array when you do founditem = item:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Also, you are using (=) the assignment operation instead of (==) relational operator, to compare. Refer to this article for help in understanding the difference between the two.
Instead of this: If stdntyear = founditem(5) And daytoday = founditem(6) Then
Use this: If (stdntyear == founditem(5)) And (daytoday == founditem(6)) Then
Now back to your main error. You continue to assign the itemarray to founditem every time you iterate (Which overwrites previous content). At the end of the Iteration you will be left with the last entry in your CSV only... So in other words, founditem will only have 1 element inside of it. If you try to pick out ANYTHING but index 0, it will throw the exception index was outside the bounds of the array
So when you try to do the following later, it throws the exception.
Dim stdntfname As String = founditem(3) 'index 3 does not exist!
To fix it do the following change:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
'NOTE: Make sure you know exactly how many columns your csv has or whatever column
' you wish to access.
Dim item() As String = line.Split(","c)
founditem(0) = item(0) 'Assign item index 0 to index 0 of founditem...
founditem(1) = item(1)
founditem(2) = item(2)
founditem(3) = item(3)
founditem(4) = item(4)
founditem(5) = item(5)
founditem(6) = item(6)
Next
For more help on how to work with VB.NET Arrays visit this site: http://www.dotnetperls.com/array-vbnet
In your line Dim item() As String = line.Split(","c) there's no guarantee that the correct number of elements exist. It's possible that one of the lines is missing a comma or is a blank trailing line in the document. You might want to add a If item.Length >= 7 and skipping rows that don't have the right number of rows. Also, remember that unlike VB6, arrays in .Net are 0 based not 1 based so make sure that item(6) is the value that you think it is.

Compare String with Strings in array

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