0

I'm working on one of my first projects. I have a listbox where I select multiple values and I would like to add each selection (selectedItem.Text) to a list of strings.

so far what I was working on is something like ..

selectedItem = new List<string>();
 var value = lstpdfList.SelectedItem.Text;
 for (int i = 0; i < lstpdfList.SelectedValue.Count(); i++)
 {
  selectedItem.Add(value);
 }

I would really appreciate any advice.

3 Answers 3

1

Iterate each item from ListBox.Items collection

foreach (ListItem  item in ListBox1.Items)
 {
  if (item.Selected)
  {
    selectedItem.Add(item.Text); // selectedImte.Add(item.Value);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Somehow my VS 2010 doesn't recognize listbox.selectedItems. SelectedItem works.
0

There is SelectedItems property of ListBox, try to iterate throught it. For example, if there is strings in your ListBox, then your code might look like this:

selectedItem = new List<string>();
foreach (string value in lstpdfList.SelectedValues)
  selectedItem.Add(value);

1 Comment

Edited my question. is ASP.NET web site in C#, can't call SelectedItems just SelectedItem
0

You can just cast them to strings:

var selectedItems = listBox1.SelectedItems
    .Cast<string>()
    .ToList();

If you have populated your ListBox with something other than just strings, just cast to whichever type you need, like so:

var selectedItems = listBox1.SelectedItems
    .Cast<WhateverYourTypeIs>()
    .Select(item => item.ToString())
    .ToList();

1 Comment

Edited my question. is ASP.NET web site in C#, can't call SelectedItems just SelectedItem

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.