Question Delete selecteditem in listview

cops

New member
Joined
Sep 4, 2008
Messages
4
Programming Experience
Beginner
Helo expert..

Please help me... I try to delete several item but always error..

error code >>>> InvalidArgument=Value of '32' is not valid for 'index'. Parameter name: index

VB.NET:
 Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        If MsgBox("Are You sure to delete all this data?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
          
            For i = 0 To ListView1.CheckedItems.Count - 1 
                ListView1.Items.Remove(ListView1.CheckedItems(i))
            Next i



        End If
           
    End Sub
 
First things first, in a ListView there is a difference between an item being checked and an item being selected. That's why there are SelectedItems and CheckedItems properties.

As for the issue, the lower and upper bounds of your loop are calculated once only at the start. When you remove an item it is no longer checked, so the number of checked items is reduced. That means that your index is going to be invalid when you have removed half the items.
 
Thanks for the reply john.

Yup.. i understand the difference between item being checked and being selected... sorry for wrong title.. it supposed to be checked item. :)

can you tell me how i suppose to write the loop ?

Thanks
 
What do you think? Use a bit of logic. Obviously a For loop is not suitable so what are the other options? Think about how you would tackle a similar problem in the physical world and you'll find that the programming solution is basically the same. Programming doesn't exist in a vacuum.
 
Back
Top