0
votes

New to vb, started about 6 months ago and just can't figure this one out. I have two listboxes where the number of items can vary but both will have the same number of items.
Listbox1
Tom
Sue
Henry

Listbox2
Shoes
Hats
Cars

I want to be able to write a line like:
comsave = LB1 & chr(32) & chr(34) & LB2

But the item from lisbox1 (LB1) and the item from listbox2 (LB2) to be at the same index.
I've tried something like this:

for each lb1 as string in listbox1.items
for each lb2 as string in listbox2.items
comsave = LB1 & chr(32) & chr(34) & LB2

But that just gives me the first item in listbox1 as many times as there are items in listbox2, before it goes on to the second item in listbox1, then it repeats.

What I want it to do is loop through all of the items in listbox1, and give the item at the same index in listbox2 for the line:
comsave = LB1 & chr(32) & chr(34) & LB2

I've been reading what I can, but the logic escapes me. Not sure if I need to split it up somehow or use an array maybe. Any help would be appreciated.

2

2 Answers

0
votes

If you want to use items at the same index then it would help to use an index:

For i = 0 To itemCount - 1
    Dim item1 = CStr(ListBox1.Items(i))
    Dim item2 = CStr(ListBox2.Items(i))

    '...
Next
0
votes
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ListBox1.Items.Clear()
    ListBox1.Items.Add("Tom")
    ListBox1.Items.Add("Sue")
    ListBox1.Items.Add("Henry")

    ListBox2.Items.Clear()
    ListBox2.Items.Add("Shoes")
    ListBox2.Items.Add("Hats")
    ListBox2.Items.Add("Cars")

    Dim s As String = ""
    For i As Integer = 0 To ListBox1.Items.Count - 1
      s &= ListBox1.Items(i) & Chr(32) & Chr(34) & ListBox2.Items(i) & vbCrLf
    Next
    MsgBox(s)
  End Sub