So a friend and myself are in a computer science course and for our final project we decided to really apply ourselves and add stuff into our assignment that we weren't taught throughout the year. Well we came to a wall when we decided to add an option to delete a selected item from a list box, the catch is in our assignment we had to use array's so when we add stuff to a list box and we delete it we clear an array and wipe an item from the list box. The thing is when we do this multiple times before re adding an item we can no longer at the same ammount of items to the list box that we set the array to. Any suggestions?

Here's the code we have for deleting a selected item..

Private Sub mnuDelete_Click()
Dim intRemove As Integer
If lstSongs.ListIndex > -1 Then
intRemove = lstSongs.ListIndex
lstSongs.RemoveItem lstSongs.ListIndex 'Deletes Selected items
End If

If intRemove = 0 Then
strSongList(0) = ""
ElseIf intRemove = 1 Then
strSongList(1) = ""
ElseIf intRemove = 2 Then
strSongList(2) = ""
ElseIf intRemove = 3 Then
strSongList(3) = ""
ElseIf intRemove = 4 Then
strSongList(4) = ""
End If
End Sub

*strSongList is declared in general and were on VB6

There are a couple of ways to do this. First and ugliest is to ReDim your array, then reload it from your list box. That way you can ensure that there are always as many items in the array as in the listbox. You do have to beware of the special case where you have deleted ALL the items from the listbox. It might look something like this:

Private Sub mnuDelete_Click()
Dim i As Integer
If Me.lstSongs.ListIndex > -1 Then
    Me.lstSongs.RemoveItem Me.lstSongs.ListIndex
    If Me.lstSongs.ListCount > 0 Then
        ReDim strSongList(Me.lstSongs.ListCount - 1)
        For i = 0 To Me.lstSongs.ListCount - 1
            strSongList(i) = Me.lstSongs.List(i)
        Next i
    End If
    MsgBox "Removed!"
End If
End Sub

This would be okay for a small list, but when the list gets long, it gets extremely expensive.

Another way to do this uses ReDim Preserve. Basically, you have to use the listindex of your listbox as the starting point for a "for...next" loop, then iterate through the remainder of strSongList, copying the next entry down one, then lop off the end of the array. It might look something like this:

Private Sub mnuDelete_Click()
Dim i As Integer
If Me.lstSongs.ListIndex > -1 Then
    For i = Me.lstSongs.ListIndex To UBound(strSongList) - 1
        strSongList(i) = strSongList(i + 1)
    Next i
    If Me.lstSongs.ListCount > 1 Then
        ReDim Preserve strSongList(UBound(strSongList) - 1)
    Else
        ReDim strSongList(0)
    End If
    Me.lstSongs.RemoveItem Me.lstSongs.ListIndex
    MsgBox "Removed!"
End If
End Sub

Hope these give you some ideas. Good luck!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.