0

I have a listbox on a form set to allow multiple selections. I want to loop through each selected item, store the selected value in a variable and do some work. I've tried many different variations of code to do this, but so far nothing has worked. Any help would be greatly appreciated! My code is below:

foreach (var item in systemList.Items)
{
    string systemName = systemList.SelectedItems.ToString();
    //do some work//
}

2 Answers 2

2

You can get all SelectedItems using below code:

var items = systemList.Items.Cast<ListItem>().Where(item => item.Selected);

You can then loop through the items

foreach (var item in items)
{
    //Access value of each item by calling item.Value
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried your suggested code and I get this error for ListItem: 'the type or namespace name 'listitem' could not be found.'
ohho... you should be able to find the relevant namespaces required to do this job; try adding one or both of these usings - using System.Web.UI; using System.Web.UI.WebControls;
1
foreach (var item in systemList.SelectedItems)
        {
            string systemName = item.ToString();
            //do some work//
        }

make sure listbox Selection mode is set to other than single!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.