MP3 Player Random Function doesn't Work - vb.net

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

Related

Same number is generated in RNG in VB.NET

I am attempting to make a random number generator in VB 16 in Visual Studio, but every time I run this I keep getting 71, I've tried making it public, sharing it and several other things, but it won't work. I am trying to make a program that has the user guess a randomly generated number, and continue guessing until they get it, but for some reason the exact same number is chosen each time. It won't work properly specifically in window app forms. How do I get a random number each time?
Public Shared Randomize()
Dim value As Integer = CInt(Int((100 * Rnd()) + 1))
Public Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Dim entervalue As String = EnterTxt.Text
Dim chances As Integer
Select Case entervalue
Case > value
ResTxt.Text = "Too big"
chances += 1
Case < value
ResTxt.Text = "Too small"
chances += 1
Case = value
ResTxt.Text = "Well done, you got it in " & chances & " tries"
End Select
End Sub
You were close! Here's a working example modifying your original logic:
Private random As Random = New Random()
Private value As Integer
Private chances As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
value = random.Next(1, 100)
chances = 0
End Sub
Private Sub EnterBtn_Click(sender As Object, e As EventArgs) Handles EnterBtn.Click
Select Case EnterTxt.Text
Case > value
chances += 1
ResTxt.Text = "Too big"
Case < value
chances += 1
ResTxt.Text = "Too small"
Case = value
chances += 1
ResTxt.Text = "Well done, you got it in " & chances & " tries"
'and reset for next attempt
value = random.Next(1, 100)
chances = 0
End Select
End Sub
Since your code is not correct it is hard to pinpoint the problem. It is also not clear what the code is supposed to do.
Try this
Private Shared PRNG As New Random ' add this
value = PRNG.Next(1, 101)'this will set value to a random number between 1 and 100 inclusive
Here's some skeleton code for you:
Dim rnd As New Random()
For i as Integer = 0 to 10
Console.WriteLine("{0,15:N0}", rnd.Next())
Next
Notice the rnd.Next() thing. Hope it helps.

Serial Communication stops working when loop is started

I have problem with serial data communication if I started a loop it is not updating the data from my weighing scale. I can't figure out how to continue the communication as well as to run the loop. The logic of my code will be in the loop so I could check the value from my integer and compare it to the data from serial data (Weighing Scale)
Private Sub conWeight_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles conWeight.DataReceived
receivedText(conWeight.ReadExisting())
End Sub
Private Sub receivedText(ByVal [text] As String)
If Me.lblWeight.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf receivedText)
Me.Invoke(x, New Object() {(text)})
Else
Dim reverseString As String = [text]
Dim revString As String = StrReverse(reverseString)
Dim clean As String
clean = revString.Replace("=", "")
Me.lblWeight.Text = clean 'append text
End If
End Sub
'this is part with loop
If binWeight = 0 Then
targetweight = CInt(txtbSilo1.Text) + CInt(txtbSilo2.Text) + CInt(txtbSilo3.Text) + CInt(txtbSilo4.Text)
If CInt(txtbSilo1.Text) > 0 Then
currentWeight = CInt(txtbSilo1.Text)
frmAutomaticControl.conControl.Open()
frmAutomaticControl.conControl.Write("motr1")
frmAutomaticControl.conControl.Close()
MsgBox("check")
Do
If binWeight >= currentWeight Then
frmAutomaticControl.conControl.Open()
frmAutomaticControl.conControl.Write("moto1")
frmAutomaticControl.conControl.Close()
Exit Do
End If
Loop
Else
End If
BunifuFlatButton1.Enabled = True
Else
MsgBox("Empty The Bin")
End If
just a couple of ideas.
1. Throw that part of the code into a background worker.
2. Cheese it and throw in an application.doevents.
3. Create a global variable that'll capture the output of each iteration of your loop that'll then feed it where it needs to go.
Just one line of code is all you need. In your loop put this above everything else.
Application.DoEvents()

Why does Windows.Media.VisualTreeHelper.GetChild(...) exit the sub?

I have a vb application with a listview.
I was testing and ended up with this sub for my dragover event:
Private Sub ListView1_DragOver(sender As Object, e As DragEventArgs) Handles ListView1.DragOver
XToolStripLabel.Text = "X:" & e.X
YToolStripLabel.Text = "Y:" & e.Y
Dim Insertion As Integer = GetInsertion(MousePosition, ListView1)
SelectionTestTSlabel.Text = "SEL " & Insertion
If CurrentlyDragging Then
Dim gr As Graphics = ListView1.CreateGraphics
Windows.Media.VisualTreeHelper.GetChild(New Windows.DependencyObject(), 0) 'I know this seems like it doesn't do much
MsgBox("") 'I actually added this later because the rest of the code did not run normally.
Dim InsertionY As Integer = 24 + (Insertion * TestItemHeight)
If MyLastInsPoint = Insertion Then
Else
ListView1.Refresh()
gr.DrawLine(New Pen(Color.Gray, 3), New Point(0, InsertionY), New Point(ListView1.Width, InsertionY))
End If
MyLastInsPoint = Insertion
End If
End Sub
I realized that the MsgBox("") doesn't popup a message box then i spammed breakpoints on the whole sub.
The sub ran as normal but after this line,
Windows.Media.VisualTreeHelper.GetChild(New Windows.DependencyObject(), 0)
the program returned to the form and did not execute the MsgBox("") line.
What's wrong with the line? The program did not even stop at the End Sub breakpoint.
New Windows.DependencyObject() has no children, so index 0 is not available
See the remaks on MSDN
Call the GetChildrenCount method to determine the total number of
child elements of a parent visual.
The value of reference can
represent either a Visual or Visual3D object, which is why the common
base type DependencyObject is used here as a parameter type.

Collection was modified; enumeration operation may not execute. VB thearding

Here is my code,
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each kthread As Thread In _threads
If kthread.Name = "123" Then
_threads.Remove(kthread)
kthread.Abort()
killedthreads += 1 'a integer
End If
Next
End Sub
I added the killedthreads integer at last as a check, vb executes the whole function good but at the last line it always throw the error said in title.
Not sure why, if killedthreads += 1 is not there then the error goes to kthread.Abort()
I had the same problem with C# with a different app earlier this year.
Edit,
Public Sub KillThread(kThread As Thread)
For i As Integer = (_threads.Count - 1) To 0 Step -1
If _threads.Item(i).Name = kThread.Name Then
_threads.Item(i).Abort()
_threads.RemoveAt(i)
End If
Next
End Sub
I did this code as Eminem said it. This gets in kThread from the running threads if something is not good or it has finished all its functions. But my problem is that, only the first thread that sends it gets abort and removed from list, others seem to get stuck once the first thread is aborted.
I create threads using,
Public Sub multiThreader(int As Integer, link As String)
Dim tCount As Integer = _threads.Count
If tCount >= Form1.ListView1.Items.Count Then
Else
Dim dy As Integer = DateTime.Now.Day
Dim mo As Integer = DateTime.Now.Month
Dim fileNum As String = dy.ToString() + "-" + mo.ToString() + "_" + int.ToString
botThread = New Thread(Sub() MainThread(fileNum, link, botThread, int.ToString()))
botThread.IsBackground = True
botThread.Name = String.Format("AutoBotThread{0}", fileNum)
_threads.Add(botThread)
botThread.Start()
End If
End Sub
and _threads is publicly, Public _threads As New List(Of Thread)
MainThread is a Public Sub which runs functions and gets return and send KillThread under certain conditions.
The problem is that you remove an item from an enumeration, before you finished iterating through it.
It's like trying to iterate from 0 to list.count, when the count changes from an iteration to another. As Bjørn-Roger Kringsjå said, you should do something like this:
For i As Integer = (_threads.count - 1) to 0 Step -1
If _threads.Item(i).Name = "123" Then
_threads.Item(i).Abort
_threads.RemoveAt(i)
killedthreads += 1 'a integer
End If
Next
By using Step -1 you make sure that an Index was out of range error will not occur, and make sure that your operations are fitted, and execute on the right order/item.

Visual Basic If Not Issue

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.