Iterating over the SelectedItems collection in a Listbox

In VB.NET I want to do something like,

Dim li as ListItem
Dim str as string = ""

For each li in mylistbox.selecteditems
    str = li.SelectedText
Next

Of course the above code does not work; but what will





Answer this question

Iterating over the SelectedItems collection in a Listbox

  • tsramkumar

    Items in a listbox are stored in the <strong>Items</strong> collection, the help list a <strong>SelectedItems</strong> to hold the selected items, so in principle your code works, though your <strong>li</strong> is an object (in general) its 'text' can be gotten calling the <strong>ToString()</strong>method, so in C# the statement reads:
    str += li.ToString() + "\n";
    probably in VB you need to use some concat() procedure (I can read, but not write VB).

    I hope this is what you searched for.

  • laq

    Try this:


    For x as Integer = 0 to ListBox.SelectedItems.Count - 1
        str = ListBox.SelectedItems(x).ToString()
    Next


    or check out this link:

    http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpref/html/frlrfsystemwindowsformslistboxclassitemstopic.asp

    Tony

  • frumbert

    Again this will not work because li as ListIem and the datatype of members in SelectedItems are incompatible types.  
  • Gediminas Bukauskas

    Correct, as stated I no VB-programmer and simply missed the meaning of the Dim statement. I thought of it as being an object, dimmed thus the code ought to work fine.
  • Iterating over the SelectedItems collection in a Listbox