How to get multiple values from ASP.NET Listbox

3.6k Views Asked by At

I have the following listbox on aspx page.

  <asp:ListBox runat="server" ID="lbA" Visible="true" 
                SelectionMode="Multiple" DataTextField="A_FACTOR" 
                DataValueField="A_ID" Width="218px"> </asp:ListBox>  

then on code behind I have the following on a button click I have the following.

string aFactor = "";

 foreach(ListItem listItem in lbA.Items)
    {
        if (listItem.Selected)
        {
            aFactor += listItem.Value + ",";
        }
    } 

when I select values (any values) from the listbox, the listItem.Selected is always false and I am not able to get values because of that. Any idea what is wrong?

2

There are 2 best solutions below

1
On BEST ANSWER

As I thought, you were doing something wrong outside the code you have provided, please see the answer of this link :

Selected item in list box is null

0
On

populate the list in

if (!IsPostBack)
{
}

at the time of form load