Milton Cardoso Milton Cardoso - 4 months ago 23
Vb.net Question

Dividing listbox items into 2 parts

I have a listbox with random items, I wanted to divide it into 2 part's and put each part in one listbox. I was able to do it, but i got a very messy code, couldn't found any help online, so I just wanna to ask if there is another way of doing it. Here's my code.

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'items count
Dim count_listbox1 As Integer = ListBox1.Items.Count - 1

'half the count - 1 (im going to use it on the for loop)
Dim metade_listbox1_1 As Integer = (count_listbox1 / 2) - 1

'half the count
Dim metade_listbox1_2 As Integer = (count_listbox1 / 2)


' ( first part of the listbox)
For i = 0 To metade_listbox1_1
list1.Items.Add(ListBox1.Items.Item(i)) 'list1 - listbox that contains 1 half
Next

' (second part of the listbox items)
For i = metade_listbox1_2 To count_listbox1
list2.Items.Add(ListBox1.Items.Item(i)) 'list2 - listbox that contains 2 half
Next

'check if number of items its even or odd, if odd, deletes the first item of the list2,
'because its the same as the last item from list1
If eo = False Then
list2.Items.Remove(list2.Items.Item(0))
End If
End Sub

Answer

Well there are many ways to split the list. The following would distribute them evenly one by one

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    For i = 0 To ListBox1.Items.Count - 1
        Dim lstbx As ListBox = If(i Mod 2 = 0, list1, list2)
        lstbx.Items.Add(ListBox1.Items.Item(i))
    Next
End Sub  

An approach with a result more like yours would be this (requires importing System.Linq).
Note that I first set size2 to the half of the count so that it will have the extra item in case the number of items is odd.

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
    Dim size2 as Integer = ListBox1.Items.Count / 2
    Dim size1 as Integer = ListBox1.Items.Count - size2

    list1.Items.AddRange(ListBox1.Items.GetRange(0, size1))
    list2.Items.AddRange(ListBox1.Items.GetRange(size1, size2))
End Sub
Comments