Search code examples
c#asp.netlistboxlistboxitems

Getting Value at Selected Indices in C# ASP.net ListBox


I am trying to get the value at selected indicies in a ListBox using ASP.net C#

MakeListBox.SelectionMode = ListSelectionMode.Multiple;
int [] indicies= MakeListBox.GetSelectedIndices();

I am going to dynamically building a select statement for a database query to an SQLDataSource. What I had hoped to be able to do was get all the selected indexes go through a loop to for the array that it returns and add each value at the specified index to a string.

I have looked through this and this but can't find what is needed to do what I have talked about.

Basically I am looking for the opposite of the IndexOf command. Or a technique that would have the same results.


Solution

  • It's not clearly obvious when looking at the ListBox control properties, but this is the best way to do it:

    foreach(ListItem li in MakeListBox.Items)
    {
       if(li.Selected)
          {
             // Append to your string list
          }
    }