Stefan Đorđević Stefan Đorđević - 5 months ago 16
Vb.net Question

VB.Net - Remove empty items in ListBox

I want to remove empty items from my listbox that looks something like this:

book1
book2

book3

book4
book5


And so on..

I have tried this code:

Dim i As Integer = 0
Do While (ListBox1.Items.Count) - 1 >= i
If String.IsNullOrEmpty(ListBox1.Items(i)) Then
ListBox1.Items.Remove(ListBox1.Items(i))
i -= 1
End If
i += 1
Loop


And i don't know why it's not working.

Answer

You can use any type of loop for any purpose but each type is best suited to certain situations a Do While loop is a poor choice in this case. The best option in this case is to use a For loop and count backwards:

For i = ListBox1.Items.Count - 1 To 0 Step -1
    If String.IsNullOrEmpty(CStr(ListBox1.Items(i))) Then
        ListBox1.Items.RemoveAt(i)
    End If
Next