I am doing my homework for my visual basic class. I have most of the code written and everything seems to be working well except for my If Not statement that catches the exception when the loop does not find what it is looking for. Anyone see a problem with the way the code looks. The file is loaded in using the browse button already and it works find when I enter information that the loop can find.
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles btnSearch.Click
'event level variables
Dim Found As Boolean
Dim Counter As Integer
'looks for entry match
If rdoAbbrev.Checked = True Then
Do Until Found Or Counter > 257
If Country(Counter).Abbreviation.ToUpper = txtAbbrev.Text.ToUpper Then
Found = True
txtCountry.Text = Country(Counter).Names
Else
Counter += 1
End If
Loop
Else
Do Until Found Or Counter > 257
If Country(Counter).Names.ToUpper = txtCountry.Text.ToUpper Then
Found = True
txtAbbrev.Text = Country(Counter).Abbreviation
Else
Counter += 1
End If
Loop
If Not Found Then
MessageBox.Show("This is not a valid entry.", "NO MATCH FOUND", MessageBoxButtons.OK)
If rdoAbbrev.Checked = True Then
txtAbbrev.Text = ""
txtAbbrev.Focus()
Else
txtCountry.Text = ""
txtCountry.Focus()
End If
End If
End If
'match not found response
'reset variables
Counter = 0
Found = False
End Sub
You If Not Found block only occurs if rdoAbbrev.Checked = True. Is that what you intended? If not, then that block of code should either be located outside of the first If block (below it) or you should have a second If block after the first While loop.
EDIT
It looks like Country is an array. You should probably use Counter >= Country.Length.
Arrays in VB.NET are 0-based. Meaning that the first item is located at Country(0), the second item is at Country(1), etc. If there are 100 elements in the array, then the last element is located at Country(99). Country(100) does not exist and will cause an Exception if you try to access it.
I'm not sure what the requirements of your homework are, but usually to iterate over the elements of a collection (array, list, etc), you would use a For loop. You can jettison from the loop early with the Exit command.
For Counter As Integer = 0 To Country.Length - 1
'...Country(Counter)
If Found Then Exit For
Next
Assuming you want the "Not Found" part to execute regardless of the rdoAbbrev.Checked property, it looks like a slight error in your logic (easily fixed).
Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSearch.Click
'event level variables
Dim Found As Boolean
Dim Counter As Integer
'looks for entry match
If rdoAbbrev.Checked = True Then
Do Until Found Or Counter > 257
If Country(Counter).Abbreviation.ToUpper = txtAbbrev.Text.ToUpper Then
Found = True
txtCountry.Text = Country(Counter).Names
Else
Counter += 1
End If
'You could also write this as:
'Found = Country(Counter).Abbreviation.ToUpper = txtAbbrev.Text.ToUpper
'If Found Then
' txtCountry.Text = Country(Counter).Names
'Else
' Counter += 1
'End If
Loop
Else
Do Until Found Or Counter > 257
If Country(Counter).Names.ToUpper = txtCountry.Text.ToUpper Then
Found = True
txtAbbrev.Text = Country(Counter).Abbreviation
Else
Counter += 1
End If
'You could also write this as:
'Found = Country(Counter).Names.ToUpper = txtCountry.Text.ToUpper
'If Found Then
' txtAbbrev.Text = Country(Counter).Abbreviation
'Else
' Counter += 1
'End If
Loop
End If
'match not found response
'Move your "Not Found" here so that the not found works regardless of the rdoAbbrev.Checked property.
If Not Found Then
MessageBox.Show("This is not a valid entry.", "NO MATCH FOUND", MessageBoxButtons.OK)
If rdoAbbrev.Checked = True Then
txtAbbrev.Text = ""
txtAbbrev.Focus()
Else
txtCountry.Text = ""
txtCountry.Focus()
End If
End If
'reset variables
Counter = 0
Found = False
End Sub
Probably you should End the If statements within their range in the code and avoid ending all your If statements at the end of the code lines. usually works for me in Basic. I think that Basic has a lot of advantages, but for me it still not a high level language that has some problems because it is so easy to work with.
Related
I'm currently writing code for a game called Caladont.
The game is about first player saying the word and the next one has to say the word that starts with last two letters of previous word.
The problem comes when I want to check if word contains less than 3 letters or if it's empty.
In the first cycle when list for filling is still empty, everything is fine.
However, after I type for example 5 or more words and type a single letter or leave it empty, it prints two "You've lost!" messages, which means that code from if statement is being ignored since it changes bool variable to false and is supposed to exit the While loop.
I've tried replacing ok = false with Exit While in condition which checks if words contains less than 3 letters and it worked, but I want to understand what is the problem.
The code can also be found here [Caladont game
GitHub](https://github.com/whistleblower91/VB.net/blob/master/Caladont%20game):
Module Module1
Sub Main()
Kaladont()
End Sub
Sub Kaladont()
Const msg As String = "You've lost!"
Dim list As New List(Of String)
Dim word As String
Dim i As Integer
Dim ok As Boolean
ok = True
While ok
Console.Write("Insert word:")
word = Console.ReadLine()
list.Add(word)
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
End If
If list.Count > 1 Then 'Skip checking first word
For i = 0 To list.Count - 2
If word.ToLower = lista(i).ToLower Then
Console.WriteLine(msg)
ok = False
End If
Next
If LastTwo(word) = "ka" Or LastTwo(word)="nt" Then
Console.WriteLine("KALADONT! You won!")
ok = False
End If
If FirstTwo(list.Last) <> LastTwo(list(list.Count - 2)) Then
Console.WriteLine(msg)
ok = False
End If
End If
End While
Check()
End Sub
Function FirstTwo(ByVal s1 As String) As String
Return Left(s1.ToLower, 2)
End Function
Function LastTwo(ByVal s2 As String) As String
Return Right(s2.ToLower, 2)
End Function
Sub Check()
Dim sign As Char
Console.WriteLine("Do you want to start new game? y\n")
sign = Console.ReadLine()
If sign = CChar("y") Then
Console.Clear()
Kaladont()
ElseIf sign = CChar("n") Then
Exit Sub
End If
End Sub
End Module
Any solutions?
Even if you set ok to false, it will still go inside the other loop, you'll need to use Else
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
Else If list.Count > 1 Then 'Skip checking first word
An other way would be to exit the while with End while.
If word.Length < 3 Or word = "" Then
Console.WriteLine(msg)
ok = False
Exit While
End If
I am a new programmer learning Visual Basic.
Right now, I'm working on a project about a softball scoreboard. I have been working on this project for a bit, and I am confused on 1 thing.
The thing I am confused on is that I put in a messagebox that said invalid input for negative numbers, but it does not delete it from lstScores and even though the message box appears it still counts as a inning input.
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
This is the code:
Public Class frmSoftballScoreboard
Const VALID_MESSAGE As String = "Enter valid runs value"
Const ONLY_MESSAGE As String = "Only seven innings are allowed"
'Declaring array
Dim scores(6) As Double
'declaring variables
Dim runs As String
Dim runningScore As Integer = 0
Dim i As Integer = 0
Dim out As Double
'page load event
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstScores.Items.Add("Runs : Running Score")
End Sub
'Enter score button
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
'Clear Menu click
Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
lstScores.Items.Clear()
lblTotal.Text = ""
'reset i to 0
i = 0
End Sub
'Exit Menu click
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
'close application
Application.Exit()
End Sub
End Class
I would really appreciate it if you could help. Thank you.
Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click
If i < scores.Length Then
'display inputbox to the user
runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
'if runs is entered
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
Exit Sub
ElseIf runs <> "" Then
'parse the value of runs
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
Else
'display error message
MessageBox.Show(VALID_MESSAGE)
lblTotal.Text = ""
End If
Else
'if runs is empty then display error message
MessageBox.Show("Enter runs for " & i & "innings")
End If
Else
MessageBox.Show(ONLY_MESSAGE)
End If
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
'calculate total runs And display on the lable
If scores(6) = 7 Then
lblTotal.Text = String.Format("final score is {0}", scores.Sum())
End If
End Sub
This is the reason why if you input invalid data it will add into lstScores, because your If statement.. is in bottom of your code, although is not recommend where you put the If else statement... Remember reading of the code is start in top to bottom.
Your first If statement is like this. If runs <> "" then ...., of course if you type the -1 value in the Input Text the Boolean will result to true, If -1 <> "" = true, then it will proceed to the statement which is
If (Double.TryParse(runs, out)) Then
'parse the runs and add it to the array scores()
scores(i) = Double.Parse(runs)
runningScore += scores(i)
'add the rainfall value to the listbox along with month name
lstScores.Items.Add(scores(i) & " :" & runningScore)
'increment the value of i
i = i + 1
This is the line of code even the value is invalid or not it still adding value in the lstScores, lstScores.Items.Add(scores(i) & " :" & runningScore)
Now after that statement you will receive a message which is :
Enter valid runs value
If runs < 0 Then
MessageBox.Show(VALID_MESSAGE)
End If
That code is the reason why you receiving the message. If you input -1 of course the result of boolean is true, why? -1 is lessthan to 0 which is true.
The thing i do is, I've insert If statement.. above, which is If runs < 0 then .... and also Exit Sub to instantly end the statement. If you input -1 to Input Text the result is something like this, if runs(-1) lessthan to 0 the Boolean result is true then it will proceed to statement which is the Message and Exit Sub.
Try my code above, and also use Breakpoints.. Hope this helps..
I just started my first project and i'm trying to make a mp3 player.
Unfortunately My "Random" causes the whole program to crash when i'm trying to open a song.
This is the error produced in Visual Studio Ultimate 2013:
An exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll but was not handled in user code
Additional information: InvalidArgument=Value of '1' is not valid for 'index'.
Please tell me what's wrong with my code, This is a link to my repository in Github, Thanks!
https://github.com/LefanTan/MP3_Player/tree/Mp3
Edit:
This line is the code that was producing the error-
Private Sub wpm_PlayStateChange(sender As Object, e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles wpm.PlayStateChange While shuffle.CheckOnClick = True tempInt = r.Next(0, ListBox1.Items.Count + 1) wpm.URL = ListBox1.Items(tempInt) End While While RepeatToolStripMenuItem1.CheckOnClick = True wpm.URL = currentSong End While End Sub
I assume this is the problematic sub:
Private Sub wpm_PlayStateChange(sender As Object, e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles wpm.PlayStateChange
While shuffle.CheckOnClick = True
tempInt = r.Next(0, ListBox1.Items.Count + 1)
wpm.URL = ListBox1.Items(tempInt)
End While
While RepeatToolStripMenuItem1.CheckOnClick = True
wpm.URL = currentSong
End While
End Sub
The line
tempInt = r.Next(0, ListBox1.Items.Count + 1)
Should be
tempInt = r.Next(0, ListBox1.Items.Count)
The syntax of this function is Random.Next(min, max) where min is inclusive and max is exclusive i.e. max isn't included in generating the random number. Because you added one to ListBox1.Items.Count (which is going to be the upper bound of the collection plus one), you went out of range.
Please Check your iteration code.
think the problem is, that your index increases
For Each item As String In My.Computer.FileSystem.GetFiles(txtfolder.Text, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.mp3")
ListBox1.Items.Add(item)
Next
So I've been working on this project for a couple of weeks, as I self teach. I've hit a wall, and the community here has been so helpful I come again with a problem.
Basically, I have an input box where a user inputs a name. The name is then displayed in a listbox. The name is also put into an XML table if it is not there already.
There is a button near the list box that allows the user to remove names from the list box. This amends the XML, not removing the name from the table, but adding an end time to that name's child EndTime.
If the user then adds the same name to the input box, the XML gets appended to add another StartTime rather than create a new element.
All of this functions well enough (My code is probably clunky, but it's been working so far.) The problem comes when I try to validate the text box before passing everything through to XML. What I am trying to accomplish is that if the name exists in the listbox on the form (i.e hasn't been deleted by the user) then nothing happens to the XML, the input box is cleared. This is to prevent false timestamps due to a user accidentally typing the same name twice.
Anyhow, I hope that makes sense, I'm tired as hell. The code I've got is as follows:
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles addPlayerButton.Click
playerTypeCheck()
addPlayerXML()
clearAddBox()
End Sub
Private Sub playerTypeCheck()
If playerTypeCBox.SelectedIndex = 0 Then
addMiner()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
addHauler()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
addForeman()
End If
End Sub
Private Sub addMiner()
If minerAddBox.Text = String.Empty Then
Return
End If
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : minerListBox.Items.Add(UCase(minerAddBox.Text))
End If
If ComboBox1.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : ComboBox1.Items.Add(UCase(minerAddBox.Text))
End If
End Sub
Private Sub addPlayerXML()
If System.IO.File.Exists("Miners.xml") Then
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim nod As XmlNode = xmlSearch.DocumentElement()
If minerAddBox.Text = "" Then
Return
Else
If playerTypeCBox.SelectedIndex = 0 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 1 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Haulers/Hauler[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 2 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Foremen/Foreman[#Name='" + UCase(minerAddBox.Text) + "']")
End If
If nod IsNot Nothing Then
nodeValidatedXML()
Else
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newPlayer As String = ""
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners")
If playerTypeCBox.SelectedIndex = 0 Then
newMinerXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
newHaulerXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
newForemanXML()
End If
End If
End If
Else
newXML()
End If
End Sub
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
minerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
haulerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
foremanValidatedXML()
End If
End Sub
Private Sub minerValidatedXML()
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = False Then
appendMinerTimeXML()
End If
End Sub
Private Sub appendMinerTimeXML()
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newStartTime As String = Now & ", "
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" & UCase(minerAddBox.Text) & "']/StartTime")
docFrag.InnerXml = newStartTime
nod2.AppendChild(docFrag)
xmlSearch.Save("Miners.xml")
End Sub
And lastly, the clearAddBox() subroutine
Private Sub clearAddBox()
minerAddBox.Text = ""
End Sub
So, I should point out, that if I rewrite the nodeValidated() Subroutine to something like:
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
appendMinerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
appendHaulerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
appendForemanTimeXML()
End If
End Sub
then all of the XML works, except it adds timestamps on names that already exist in the list, which is what i'm trying to avoid. So if I haven't completely pissed you off yet, what is it about the minerValidated() subroutine that is failing to call appendMinerTimeXML()? I feel the problem is either in the minerValidated() sub, or perhaps clearAddBox() is somehow firing and I'm missing it? Thanks for taking the time to slog through this.
Edit: Clarification. The code as I have it right now is failing to append the XML at all. Everything writes fine the first time, but when I remove a name from the list and then re-add, no timestamp is added to the XML.
You need to prevent the user accidentally typing the name twice.(Not sure if you mean adding it twice)
For this I believe you need to clear the minerAddBox.Text in your addminer() if this line is true.
minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True
minerAddBox.Text = ""
Return
Now it will return back to your addplayerXML which will Return to your clearbox(), since you have this in your addplayerXML()
If minerAddBox.Text = "" Then
Return
Now you get to your clearbox() (Which is not really needed now since you cleared the minerAddBox.Text already)
when I remove a name from the list and then re-add, no timestamp is added to the XML.
your minerValidatedXML() is true, because you are not clearing the textbox when you re-add a name to the list box. Or you may need to remove the existing listbox item if it is the same as the textbox
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
minerListBox.Items.remove(UCase(minerAddBox.Text))
I am trying to create a Loop that will read through the information on my ListView through the SubItem to find the text that matches the text in my Textbox whenever I hit the search button and Focuses the listbox onto the matched text. Below is what I have but it keeps telling me that the value of string cannot be converted. I am also pretty sure that my numbers wont loop correctly but I am not really sure how to cause them to loop endlessly till end of statement.
Dim T As String
T = Lines.Text
For r As Integer = 0 to -1
For C As Integer = 0 to -1
If List.Items(r).SubItems(C).Text = Lines.Text Then
List.FocusedItem = T
End If
Next
Next
End Sub
I don't understand your code, but I do understand the question. Below is example code to search all rows and columns of a listview. Search is case insensitive and supports a "find next match" scenario. If a match or partial match is found in any column the row is selected. TextBox1 gets the text to find. FindBtn starts a new search.
Private SrchParameter As String = ""
Private NxtStrtRow As Integer = 0
Private Sub FindBtn_Click(sender As Object, e As EventArgs) Handles FindBtn.Click
If Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
SrchParameter = TextBox1.Text
NxtStrtRow = 0
SearchListView()
End If
End Sub
Private Sub ListView1_KeyDown(sender As Object, e As KeyEventArgs) Handles ListView1.KeyDown
If e.KeyCode = Keys.F3 Then
SearchListView()
End If
End Sub
Private Sub SearchListView()
' selects the row containing data matching the text parameter
' sets NxtStrtRow (a form level variable) value for a "find next match" scenario (press F3 key)
If ListView1.Items.Count > 0 Then
If SrchParameter <> "" Then
Dim thisRow As Integer = -1
For x As Integer = NxtStrtRow To ListView1.Items.Count - 1 ' each row
For y As Integer = 0 To ListView1.Columns.Count - 1 ' each column
If InStr(1, ListView1.Items(x).SubItems(y).Text.ToLower, SrchParameter.ToLower) > 0 Then
thisRow = x
NxtStrtRow = x + 1
Exit For
End If
Next
If thisRow > -1 Then Exit For
Next
If thisRow = -1 Then
MsgBox("Not found.")
NxtStrtRow = 0
TextBox1.SelectAll()
TextBox1.Select()
Else
' select the row, ensure its visible and set focus into the listview
ListView1.Items(thisRow).Selected = True
ListView1.Items(thisRow).EnsureVisible()
ListView1.Select()
End If
End If
End If
End Sub
Instead of looping like that through the ListView, try using a For Each instead:
searchstring as String = "test1b"
ListView1.SelectedIndices.Clear()
For Each lvi As ListViewItem In ListView1.Items
For Each lvisub As ListViewItem.ListViewSubItem In lvi.SubItems
If lvisub.Text = searchstring Then
ListView1.SelectedIndices.Add(lvi.Index)
Exit For
End If
Next
Next
ListView1.Focus()
This will select every item which has a text match in a subitem.
Don't put this code in a form load handler, it won't give the focus to the listview and the selected items won't show. Use a Button click handler instead.
This is the easiest way to search in listview and combobox controls in vb net
dim i as integer = cb_name.findstring(tb_name.text) 'findstring will return index
if i = -1 then
msgbox("Not found")
else
msgbox("Item found")
end if