Visual basic list box - vb.net

I am trying to get each item in a list box into a string array. However, I keep getting an index error and I am not sure why. I am doing this so i can perform a LINQ on the array. Here is the error and the code in question. Thank you for any help in advance.
Error:
InvalidArgument=Value of '16' is not valid for 'index'.
Parameter name: index
Code:
Dim size As Integer = lstBoxSeats.Items.Count()
Dim seats(size) As String
For i = 0 To size
seats(i) = lstBoxSeats.Items(i).ToString()
Next

Your array is zero based, the count is actual number of items. You need to subtract 1 from the count for your index.
i.e.
Correction: just realized that you were using count to dimension your seats array which is leaving a empty position in your seats array
Dim size As Integer = lstBoxSeats.Items.Count()-1 'Subtract 1 here instead of in the For statement
Dim seats(size) As String
For i = 0 To size
seats(i) = lstBoxSeats.Items(i).ToString()
Next

This is because index is zero based i.e starts from 0 while Count is the amount of items which starts from 1, so if there are 16 items it means that maximum index is 15 (0-15) and count is 16(1-16)

Related

How to pass Value from Last Loop?

I have been attempting many ways to retrieve 2 collections together, while the first collection holds a comma-separated value in a column, we can not find a solution to passing the first collection value to the second For Each.
This code simply retrieves database rows and adds each result to our list control using the Add() method.
Dim transferstable As New DataTable
count = 0
For Each row As DataRow In transferstable.Rows
Dim name = Truncate(row.Item("name"), 42)
ListControl1.Add(name, row.Item("username")", row.Item("added"), avatars, row.Item("online"), images(count), 0)
count += 1
Next
Problem
We need to nest the loops, so we get the value from the first collection from the "avatars" column (image1,image2,image3) and call it from Add() - 4th parameter.
We only get always 1 string result into the view, while the actual query reports many rows with 2 strings (image1, image2) so I tried this:
Dim lst As New List(Of String) From {
transferstable.Rows(0).Item(8)
}
count = 0
For Each item As String In lst
For Each row As DataRow In transferstable.Rows
Dim name = Truncate(row.Item("name"), 42)
ListControl1.Add(name, row.Item("username")", row.Item("added"), item, row.Item("online"), images(count), 0)
count += 1
Next
Next
And the still the same single result! (8) is the GROUP_CONCAT column for "avatars" How do we pass this list over to the 4th parameter?
We want to retrieve these as URL remote images and render them to view with Bitmap.
Expected result:
A list of 15x15 pictures that represent each split result from GROUP_CONCAT(avatars)
I've been at all different ways to do this for most of the day, I know nesting is the right direction but I can't figure out why only 1 result is coming back (image1 - not image1,image2, etc.)
Some physical image files do not exist anymore, so rendering that to view also has it halt after a few single string results, so it quits and gives an error, like a 404 but does not proceed with the 180 other rows.
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/for-each-next-statement

Index Out Of Range (Range Is Variable)

So I'm trying to return all the column names in my datagridview. The code below returns the column names except at the end, I a message stating Index was out of range I assume this is because I have less than 500 columns in my datagridview.
The 500 could in theory be any amount, some might only have 20 columns, others might have 300 columns.
How would I go about clearing up this error?
Dim c As Integer
For cn = 0 To 500
c = c + cn
'Debug.Print(cn)
Debug.Print(DataGridView1.Columns(cn).Name)
Next cn
"Index out of range" exception can happen when you are trying to access a member of collection under index that doesn't exist
Lets take your example - you getting error here DataGridView1.Columns(cn) because your cn has a value which doesn't exist in DataGridView1.Columns. For example, if you have 2 columns, your indexes are 0 and 1. If you try to ask for DataGridView1.Columns(2) - you will get this exception. So, as mentioned above in comments, when dealing with collections you either use For Each loop or you use For... count -1 loop
This is correct code:
For i as Integer = 0 To DataGridView1.Columns.Count - 1
Debug.WriteLine(DataGridView1.Columns(i).Name)
Next
Example of For Each
For Each s as String In myStrings ' myStrings can be List(Of String)
Debug.WriteLine(s)
Next

How to read first 2 number of every line in listbox vb . Net

I have listbox has lines like this
12345678%32=5
4663578877fg
6883346899
,,,etc
How can I get the first two number of every line to be like this
12
46
68
BTW the listbox has only numbers in first of every line
Thanks!
myListBox.Items.Add("1234")
myListBox.Items.Add("567")
myListBox.Items.Add("890")
For position As Integer = 0 To myListBox.Items.Count - 1
myListBox.Items(position) = CStr(myListBox.Items(position)).Substring(0, 2)
Next
EDIT
We can use the RichTextBox.Lines property that returns a array of String. Each String in the array represents a line in the RichTextBox. If you want to store the first two digits in an array, you can try :
Dim intValues(Convert.ToInt32(RichTextBox1.Lines.Length)) As Integer 'Stores the digits
For position As Integer = 0 To Convert.ToInt32(RichTextBox1.Lines.Length) - 1
intValues(position) = Convert.ToInt32(RichTextBox1.Lines(position).Substring(0, 2))
Next

Random shuffling of elements in an array between 2 indexes VB.NET

I'm trying to shuffle elements between a certain number of indexes.
Dim rng As New Random()
For placeHolder As Integer = min To max Step -1
Dim swapIndex As Integer = rng.Next(min, max)
Dim temp As Object = myList(placeHolder)
myList(placeHolder) = myList(swapIndex)
myList(swapIndex) = temp
Next
Where 'min' is the value of the lowest index and 'max' is the value of the highest index. However each time I have tried it doesn't seem to be shuffling randomly (it always comes out alphabetically instead).
Try this:
Dim rng As New Random()
For placeHolder as Integer = min To max-1 Step 1
Dim swapIndex as Integer = rng.Next(placeHolder +1, max)
Dim temp as Object = myList(placeHolder)
myList(placeHolder) = myList(swapIndex)
myList(swapIndex) = temp
Next
The changes?
I changed the max value being stepped over to 1 less than the end so that you don't waste time trying to swap the end with itself. I also changed the Step to +1 because min < max from your description. I changed the minimum random value to placeholder + 1 because I don't want to re-swap what I've already swapped. This last change is optional though.
if min is the lowest and max is the highest, then your loop should not have Step -1 in it. That will cause the loop to never execute.

Array of Integers Comparing Integers VB.NET

Basically I have and array of integers that vary in size. I need to compare each number to each other number and display which number is repeated. For example:
Dim ints() As Integer = {1,2,2,5,4,6}
The number that shows up more than once is 2.
How can I run through the array and compare each integer with the numbers in the array. I tried a for loop but it didn't return the value I was looking for. I am new to VB.NET and do not understand fully.
Dim ints() As Integer = {1,2,2,5,4,6}
Dim repeatedNumbers = ints.GroupBy(Function(intValue) intValue) _
.Where(Function(grp) grp.Count > 1)
For each grp in repeatedNumbers
Console.WriteLine("Number {0} is repeated {1} times", grp(0), grp.Count)
Next
What this code does:
We first call GroupBy, which groups items by their value. The Function gets the grouping key, in this case we simply group by the array's value itself. This call returns a sequence of
groups. There is one group for every unique value in the array. The
group contains all items that correspond to a unique value. So if a value appears twice in the array, there will be a group which contains two ints with this value.
We call Where to filter groups. We only want groups for which the count is greater than one, so that only duplicate values are considered.
We then loop through the result. grp(0) gives us the first number in the group (we could have picked any number in the group, since all numbers in a group are the same!) and the Count property gives us the number of repetitions.
I would try it with something like this:
Dim ints() As Integer = {1, 2, 2, 5, 4, 6}
Array.Sort(ints)
For i = 1 To ints.GetUpperBound(0)
If ints(i) = ints(i - 1) Then MessageBox.Show(String.Format("{0} is repeated", ints(i)))
Next
Doing it like this on a sorted array keeps down the nesting.
I've not tested this but it should be along the right lines.
You could use LINQ to find the duplicates:
Dim repeating = (From n In ints
Group By n Into Dups = Group
Where Dups.Count > 1
Select Dups.First).ToArray()
This returns an Array of integers which only contains numbers that are not unique in the original array.
So this displays the repeating number(s):
MessageBox.Show(String.Format("Duplicates found: {0}", String.Join(","c, repeating)))