Search code examples
c#winformsvisual-studio-2010listbox-control

C# multiple select listbox selected item text


I have a list-box, I want to loop through all the selected items and get each selected items text value.

for (int i = 0; i < lstFieldNames.selectedItems.Count; i++)
{
string s = lstFieldNames.SelectedItems[i].ToString();
}

the value of s is "{ Item = ADDR }"

I don't need the { Item = }, I just want the text "ADDR".

What am I doing wrong, I tried a few things and nothing seems to work for me.


Solution

  • Well, this is a Winforms question because an ASP.NET ListBox has no SelectedItems property(notice the plural). This is important since a Winforms ListBox has no ListItems with Text and Value properties like in ASP.NET, instead it's just an Object.

    You've also commented that the datasource of the ListBox is an anonymous type. You cannot cast it to a strong typed object later.

    So my advice is to create a class with your desired properties:

    class ListItem {
        public String Item { get; set; }
    }
    

    Create instances of it instead of using an anonymous type:

    var items = (from i in xDoc.Descendants("ITEM") 
                 orderby i.Value 
                 select new ListItem(){ Item = i.Element("FIELDNAME").Value })
                .ToList();
    

    Now this works:

    foreach (ListItem i in lstFieldNames.SelectedItems)
    {
        String item = i.Item;   
    }
    

    Note that my ListItem class is not the ASP.NET ListItem.