1
votes

I'm using vb.net form.

I have 3 listboxes each one contains many items (listbox1 , listbox2,listbox3) and another empty listbox (listbox4) im trying to add first three listboxes items into the 4th listbox

ex: ) listbox1 first items is 'A' , listbox2 first items is 'b' , listbox3 first items is 'c' now listbox4 first item must be "Abc"

The problem is I't's work but keep loop the items. here is my code :

For i = 1 To ListBox1.Items.Count - 1

       For j = i To ListBox2.Items.Count - 1

           For k = j To ListBox3.Items.Count - 1

               ListBox4.Items.Add(ListBox1.Items(j).ToString + ListBox2.Items(j).ToString + ListBox3.Items(k).ToString)

               Exit For
           Next
       Next
   Next
1

1 Answers

1
votes

You have nested the loops. This means that the inner loops are repeated at each loop of the outer loops. E.g. If the three list boxes have 3, 4, and 6 elements the most inner loop will loop 3 x 4 x 6 = 72 times!

Instead make only one loop:

Dim n As Integer = _
    Math.Min(ListBox1.Items.Count, Math.Min(ListBox2.Items.Count, ListBox3.Items.Count))

For i As Integer = 0 To n - 1
    ListBox4.Items.Add( _
        ListBox1.Items(i).ToString + _
        ListBox2.Items(i).ToString + _
        ListBox3.Items(i).ToString)
Next