Search code examples
c#for-looplistboxlistboxitem

Listbox.items[i].Selected only captures the first selected item


I'm trying to loop through and all my selected values within a Listbox and add them to a string. However when I do the loop below all I get is the first selected item in the Listbox and none of the subsequent selected items. Can anyone see where I'm going wrong?

I've tried stepping through it and it just doesn't seem to be realising that the items have been selected. Maybe .Selected doesn't work as I'm expecting, which is for all items which have been selected to be picked up.

       string selectedItem = "";
            if (impactedServicesData.Items.Count > 0)
            {
                for (int i = 0; i < impactedServicesData.Items.Count; i++)
                {
                    if (impactedServicesData.Items[i].Selected)
                    {
                        if (selectedItem == "")
                        {
                            selectedItem = impactedServicesData.Items[i].Value;
                        }
                        else
                        {
                            selectedItem += "," + impactedServicesData.Items[i].Value;
                        }
                    }
                }
            }

Solution

  • Make sure you have set the SelectionMode correctly to allow multiple item selection.

    Then, for a multi-selection ListBox, you can use SelectedItems to get a collection of all the selected items.

    Your code could be re-written as:

    string selectedItem = "";
    foreach (var s in impactedServicesData.SelectedItems)
    {
        if (selectedItem == "")
        {
            selectedItem = s.Value;
        }
        else
        {
            selectedItem += "," + s.Value;
        }
    }
    

    Also consider using a StringBuilder when concatenating many strings in a loop.