How to take Items from List in Visual Basic - vb.net

I am trying to take Items that I have already added to a list.
Dim lista As New List(Of String)
n = 2
i = 0
Do While i < n + 1
Randomize()
a = Int(Rnd() * 4) + 1
If a = 1 Then
lista.Add("1b")
ElseIf a = 2 Then
lista.Add("2b")
ElseIf a = 3 Then
lista.Add("3b")
ElseIf a = 4 Then
lista.Add("4b")
End If
i = i + 1
Loop
Lets imagine that the list i got was {2b,4b,1b}. Now i want to know how to get lets say just 2b from the list as a first Item and then delete it from the list.

This would be a good place to use a Queue(Of ).
Dim item As String
item = queuea.Dequeue
But List(Of ) has an indexer so you can just use it like an array:
Dim item As String
item = lista(0)
' Then remove the first item:
lista.RemoveAt(0)

Use the .net Random class instead of the old VB6 methods. Calling Random.Next(Interger1, Integer2) will return an Integer equal to or greater than Integer1 and less than Integer2. Note that since the values are so limited there is a good chance of having duplicates in the list.
Although multiple ElseIfs will work, a Select Case is easier to read and less typing.
I put the contents of the list in a ListBox so we could see what was going on. I used the Remove method of List(Of T) then rebind the ListBox.
Private lista As New BindingList(Of String)
Private rand As New Random
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BuildList()
ListBox1.DataSource = lista
End Sub
Private Sub BuildList()
Dim i = 0
Dim a As Integer
Do While i < 3 'since n never changes just use the literal value
a = rand.Next(1, 5)
Select Case a
Case 1
lista.Add("1b")
Case 2
lista.Add("2b")
Case 3
lista.Add("3b")
Case 4
lista.Add("4b")
End Select
i = i + 1
Loop
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Remove from list
lista.Remove(ListBox1.SelectedItem.ToString)
End Sub

Related

VB.NET Random unique generator

I'l trying to generate a unique random number generator with the snippet of code from below, but it's not working. The IF section is suppose to test if it's the first random number generated, if it is, it's suppose to add the first random number to the ArrayList, if it's not the first random number, it's supposed to check if the random number is already in the ArrayList and if it's in the ArrayList it's suppose to MsgBox and generate a new unique random number that is not already in the ArrayList and add it to the ArrayList, but it's not doing any of those. Any help would be greatly appreciated.
Public Class Form1
Dim r As New Random
Dim dLowestVal As Integer = 1
Dim dHighestVal As Integer = 26
Dim dItemAmount As Integer = 1
Dim RollCheck As New HashSet(Of Integer)
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
lblItemAmount.Text = dItemAmount
If dItemAmount = 1 Then
RollCheck.Add(Val(lblRandomNo.Text))
ElseIf (RollCheck.Contains(Val(lblRandomNo.Text))) Then
MsgBox("Already Exists")
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
RollCheck.Add(Val(lblRandomNo.Text))
End If
dItemAmount = dItemAmount + 1
Thanks in advance.
You could replace your whole method with this simple one
' This is globally declared at the top of your form
Dim values As New List(Of Integer)
' This is called when you construct your form
' It will store consecutive integers from 1 to 25 (25 elements)
values = Enumerable.Range(1, 25).ToList()
This is the method that extract an integer from your values that is not already used
Private Sub Roll()
' Get an index in the values list
Dim v = r.Next(0, values.Count)
' insert the value at that index to your RollCheck HashSet
RollCheck.Add(values(v))
' Remove the found value from the values list, so the next call
' cannot retrieve it again.
values.Remove(values(v))
End Sub
And you can call it from the previous event handler in this way
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
if values.Count = 0 Then
MessageBox("No more roll available")
else
Roll()
End Sub
End Sub
The point of the HashSet is that since it doesn't allow duplicates you can just check the return value of Add() to determine whether the number was successfully inserted or if it already exists in the list.
If you want to keep trying until it succeeds all you have to do is wrap it in a loop:
If dHighestVal - dLowestVal >= RollCheck.Count Then
'If the above check passes all unique values are MOST LIKELY already in the list. Exit to avoid infinite loop.
MessageBox.Show("List is full!")
Return 'Do not continue.
End If
Dim Num As Integer = r.Next(dLowestVal, dHighestVal)
'Iterate until a unique number was generated.
While Not RollCheck.Add(Num)
MessageBox.Show("Already exists!")
Num = r.Next(dLowestVal, dHighestVal)
End While
lblRandomNo.Text = Num
An alternative way of writing the loop is: While RollCheck.Add(Num) = False.

Compare the values of two listboxes and add the non-equivalent values to a third listbox

My knowledge of programming is not too extensive but I have just finished my second year of higher education in computer engineering and have taken a few low level programming courses.
In Visual Basic, I am having trouble comparing the values of two ListBox controls and putting the values that aren't the same into another ListBox.
I need to compare the items of ListBox2 to the items of ListBox1 and if there are any items in ListBox2 that are not in ListBox1, add them to ListBox3. I do not need to find the items in ListBox1 that are not in ListBox2. I cannot use a loop to compare their values based on index because these lists are of names which will be constantly added to and removed from. I also cannot sort these ListBoxes.
There was an example for C# that I found here that used LINQ (I don't really know what that is) to compare the lists and then add the result to a TextBox control. However, I need to know how to add them to a ListBox and not a TextBox.
[EDIT] The example that I have tried is this:
Dim result As List(Of String) = (From s1 As String In Me.ListBox1.Items Where Not Me.ListBox2.Items.Contains(s1) Select s1).ToList()
Me.TextBox1.Text = String.Join(Environment.NewLine, result)
Dim one As ListBox = New ListBox()
Dim two As ListBox = New ListBox()
Dim three As ListBox = New ListBox()
Dim unique As Boolean = True
For i As Integer = 0 To one.Items.Count
For j As Integer = 0 To two.Items.Count
If (one.Text = two.Text) Then
unique = False
Else
two.SelectedIndex = j
End If
Next
If (unique) Then
three.Items.Add(one.Text)
Else
one.SelectedIndex = i
unique = True
End If
Next
I believe this may be what you're looking for. What it does is compares each value in Listbox one to all values in Listbox two and if a value is seen to be a duplicate the Boolean flag unique is switched to false and the item is not added to Listbox three.
I think i found the solution:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox3.Items.Clear()
Dim result As List(Of String) = (From s1 As String In Me.ListBox2.Items Where Not Me.ListBox1.Items.Contains(s1) Select s1).ToList()
For Each l In result
ListBox3.Items.Add(l)
Next
End Sub
or
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim result As List(Of String) = (From s1 As String In Me.ListBox2.Items Where Not Me.ListBox1.Items.Contains(s1) Select s1).ToList()
For Each l In result
If Not ListBox3.Items.Contains(l) Then
ListBox3.Items.Add(l)
End If
Next
End Sub
Try which works best for you :)

Visual Basic Windows Form - Help Loading picture corresponding to numerical value

Hello i am trying to make a texas hold'em style game and im at the point where i filled an array with numbers 1-52 randomly assorted. I first pull the value from the first index of the array and have the corresponding card picture be set to a picturebox value. I have saved the 52 card .png files in my resources as well. These pictures are also saved with their names as 1.png, 2.png, 3.png.... etc depending the suit and value.
I am sorting the values as 1-13 spades (2-ace), 14-26 hearts, 27-39 diamonds, 40-52 clubs.
I also just saw i should probably use a global counter to keep track of the deck position.
Public Class Form1
Dim Deal As MsgBoxResult
Dim CardDeck As New Random
Dim Counter As Integer = 1
Dim CardCount(52) As Integer
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnStart.Click
Deal = MessageBox.Show("Would you like to start a Game?", "Texas Holde'em", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
ShuffleDeck()
CalculateFirst3Cards()
End Sub
Private Sub ShuffleDeck()
If Deal = MsgBoxResult.Yes Then
For num As Integer = 1 To CardCount.Length - 1
Dim DeckValue As Integer = CardDeck.Next(1, 52)
CardCount(Counter) = DeckValue
Counter += 1
Next
End If
End Sub
Private Sub CalculateFirst3Cards()
Dim counter As Integer = 1
For num As Integer = 1 To 3
Dim hold As Integer = CardCount(counter)
Dim hold1 As String = Convert.ToString(hold)
River1.Image = My.Resources.
counter += 1
Next
End Sub
End Class

setting every value in a list to something in vb

Let's say I want to set the property of every item in a list like this:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim test As New List(Of PictureBox)
For q = 1 To 25
Dim picbox As New PictureBox
test.Add(picbox)
Next
timer tick
test.Item(everything in list).Top -= 3
End Sub
Can I do it all at once instead of iterating and setting each value separately?
You should just update the color before adding it to your list:
For q = 1 To 25
picBox.BackColor = Color.AliceBlue
test.Add(picbox)
Next
As an aside, do you realize that you are adding the same item 25 times? If you want different instances you'd need to create a new one in your loop:
For q = 1 To 25
picBox = New PictureBox
picBox.BackColor = Color.AliceBlue
test.Add(picbox)
Next
Just for fun, you could rewrite your entire snippet like so to get a list of 25 PictureBoxes:
Dim test = Enumerable.Range(1,25) _
.Select(Function(i) New PictureBox With {.BackColor = Color.AliceBlue}) _
.ToList

Want this random number generator to generate 10 answers and add to a list box

I am trying to keep some skills by writing a application during my semester break at school and have found some issues I don't know the answer to.
I am trying to get this code to generate 10 results and concatenate them to a ListBox named lstPhoneNumbers. Here is what I've tried:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Calculate Random Prefix based upon selected city
If lstBoxCity.SelectedItem.ToString = "Bethany" Then
' Initialize the random-number generator.
Randomize()
Dim Bethany As String() = {"298", "342", "443", "644", "712", "755", "759", "777", "779", "847"}
' Generate random value between 1 and then length of your Bethany array
Dim randomBethany As String = Bethany(CInt((Bethany.Count * Rnd()) + 1))
MsgBox(randomBethany.ToString)
End If
* Edited for Steven Doggart**
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Calculate Random Prefix based upon selected city
If lstBoxCity.SelectedItem.ToString = "Bethany" Then
Dim Bethany As String() = {"298", "342", "443", "644", "712", "755", "759", "777", "779", "847"}
For i As Integer = 0 To 9
lstPhoneNumbers.Items.Add(Bethany(RandomPrefix.Next(0, Bethany.Count - 1)))
Next
End If
End Sub
You really should be using the Random class rather than the old-VB6-style Rnd method. Even if you are using Rnd, you should, ideally, only be calling Randomize once, when the program starts, not every time the button is clicked. To do this with the Random class, first you should create a Random object as a private field on your form, like this:
Public Class MyForm
Private rand As New Random()
' ...
Then, in your button click event handler, you need to create a For loop which generates 10 random numbers, adding each one to the ListBox control as it does so:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'...
For i As Integer = 0 to 9
lstPhoneNumbers.Items.Add(Bethany(rand.Next(0, Bethany.Count - 1)))
Next
End Sub