using listbox to delete records

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,530
Location
Lansing, MI; USA
Programming Experience
10+
i have a listbox bound to a dataset and what i would like to do is allow the user to select multiple items from the listbox then loop through the selectedindicies to delete the rows, this is the code thusfar:

VB.NET:
For x As Integer = lstContacts.SelectedIndices.Count - 1 To 0 Step -1
   DsContactList1.Contacts.Rows(lstContacts.SelectedIndices.Item(x)).Delete()
Next x

it works if up to two are selected, but if there are 3 or more selected i get an error "Index was outside bounds of the array"

any ideas? oh and this is VS 2003 not VS 2005
 
I suppose it is the index of the listbox that goes out of bounds? (and not the dataset)

Say you have 3 selecteditems out of 5 items
x will equal 2 -> row with the last selectedindex is deleted from the dataset
x will equal 1 -> Since lstContacts is bound to the dataset that was just modified, maybe the other selectedindices are already lost at this point?
I'm not sure, the logic of your loop seems ok to me, though.

To be safe, I would use that loop to just add the selectedindices to an array. Afterwards, use the array to delete the correct rows from the dataset. That way, lstContacts won't give problems.
 
Last edited:
i could try using an array

weird thing is microsoft has an example doing the same thing (just not with a dataset) and it apparently works for them, which is why i'm confused right now

edit:
this appears to work:
VB.NET:
                        Dim Indicies As New ArrayList
                        For int As Integer = 0 To lstContacts.SelectedIndices.Count - 1
                            Indicies.Add(lstContacts.SelectedIndices.Item(int))
                        Next int
                        For x As Integer = Indicies.Count - 1 To 0 Step -1
                            'MessageBox.Show(x.ToString)
                            DsContactList1.Contacts.Rows(CInt(Indicies(x))).Delete()
                        Next x

using a separate arraylist, i don't know why though, but it works
 
Back
Top