Results 1 to 4 of 4

Thread: [RESOLVED] Listbox: Removing All SelectedItems

  1. #1

    Thread Starter
    Fanatic Member Emcrank's Avatar
    Join Date
    Jan 2009
    Posts
    566

    Resolved [RESOLVED] Listbox: Removing All SelectedItems

    Ok i want to remove all selecteditems i tried to use this loop but it didn't work
    Code:
            Dim a As String
            For Each a In History_Textbox.SelectedItems
                History_Textbox.Items.Remove(a)
            Next
    How do i do it because that just didn't do anything

  2. #2
    Frenzied Member MaximilianMayrhofer's Avatar
    Join Date
    Aug 2007
    Location
    IM IN YR LOOP
    Posts
    2,001

    Re: Listbox: Removing All SelectedItems

    You can't modify a collection that is enumerated with 'for each'. Otherwise you might end up retrieving objects that no longer exist, exactly what you are doing now. What you can do, however, is the following:

    Code:
    For Each Object o In _
        From Object x In History_TextBox.SelectedItems _
        OrderBy History_TextBox.Items.IndexOf(x) Descending _
        Select x
        History_TextBox.Items.Remove(o)
    Next
    Or alternatively:

    Code:
    For i As Integer = History_TextBox.SelectedIndices.Count - 1 To 0 Step -1
        History_TextBox.Items.RemoveAt(History_TextBox.SelectedIndices(i))
    Next
    One is LINQ, the other is reverse looping through indices. In order to ensure that the indices remain the same, you must remove items from the back to the front.

  3. #3
    Junior Member
    Join Date
    Jun 2009
    Posts
    19

    Re: Listbox: Removing All SelectedItems

    Use Items.RemoveAt(a)

  4. #4

    Thread Starter
    Fanatic Member Emcrank's Avatar
    Join Date
    Jan 2009
    Posts
    566

    Re: Listbox: Removing All SelectedItems

    thankyou for help,
    Code:
    For i As Integer = History_TextBox.SelectedIndices.Count - 1 To 0 Step -1
        History_TextBox.Items.RemoveAt(History_TextBox.SelectedIndices(i))
    Next
    worked perfectly

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width