Question Accessing Multiple Items in a Listbox

digitaldrew

Well-known member
Joined
Nov 10, 2012
Messages
167
Programming Experience
Beginner
I've been trying to think about the best way to do this..Hopefully someone here can give me some advice/input!

I have a listbox and the items in it will vary. Sometimes it might have 300 items, it could have 406, 1029..any number of items basically.
I have an API I'm using which I'm using and will pass each item in the listbox through. This API will let me take and pass upto 50 items at once..

Now, I'm assuming the best way to go about doing this would be to throw these items into an array and then access them 50 at a time..However, I could see this posing a problem if there are 303 items in there because after the 6th run there will only be 3 items left.

What would be the best way to handle this? I want to pass up to 50 items in each request (these items have to be placed into the API http request I'm making), but each request might not actually have 50 items in it...

Thanks in advance!
 
You can throw a bit of LINQ at the problem and do something like this:
For i = 0 To Integer.MaxValue
    Dim page = Me.ListBox1.Items.Cast(Of Object).Skip(i * 50).Take(50).ToArray()

    If page.Length = 0 Then
        Exit For
    End If

    'Use page here.
Next
That will repeatedly give you an Object array with up to 50 elements. Skip and Take automatically handle situations where the number of items is less than the number specified so you don't even have to think about it. You can obviously adjust that as necessary, e.g. cast as type String instead of Object.
 
Thanks for the response! One other issue I'm running into now though..

Now that I have the array built (using strings instead of objects)..I want to put them together, and add some standard text before each one. To do that, I'm using string.join..Here is the code I've been testing with

VB.NET:
Dim JoinDomains As String = String.Join("&domain" & i & "=", page)

What I'm left with is:
domain1.com&domain0=domain2.com&domain0=domain3.com&domain0=domain4.com..etc.

When the correct format should be:
&domain0=domain1.com&domain1=domain2.com&domain2=domain3.com&domain3=domain4.com

Obviously the "i" is misplaced in my code because I'm doing that inside the loop you created in your original response, that makes sense as to why I'm getting "domain0" everytime..But, what's the best way to go about handling this? Make another loop that now loops through "page" and creates the integer for "domain"?

Thanks!!
 
You might be able to just create a new int inside of the loop and set that to i (eg "Dim intTemp as Integer = i"), and then use that variable inside the LINQ...
 
Back
Top