Search code examples
c#asp.netmvp

Listbox multiitem selection on selectedindex change?


I have a list box in which i have multiple value

<asp:ListBox ID="lstbox" runat="server" SelectionMode="Multiple" Width="120px">
<asp:ListItem Value="0">None</asp:ListItem>
<asp:ListItem Value="8">Rohan</asp:ListItem>
<asp:ListItem Value="16">Jems</asp:ListItem>
<asp:ListItem Value="64">Tena</asp:ListItem>
<asp:ListItem Value="4">Marry</asp:ListItem>
<asp:ListItem Value="2">Pinky</asp:ListItem>
<asp:ListItem Value="32">Coral</asp:ListItem>
<asp:ListItem Value="1">Dev</asp:ListItem>
<asp:ListItem Value="128">Sam</asp:ListItem>
</asp:ListBox>

at once i want to select either one item or more than one and one selected index change i am calling a method

    protected void lstbox_SelectedIndexChanged(object sender, EventArgs e)
    {
        Presenter.getRoles();//filling a grid from database call
    }

    public void getRoles()
    {
        int proid = 0;
        int per=0;
        if (View.UPrivileges.Count > 0)
        {
            proid = Convert.ToInt32(View.UPrivileges.SelectedValue);//listbox selection
            per= Convert.ToInt32(View.Products.SelectedValue);// i have a ddl product checking the value
        }
        if (proid != 0 || per !=0)
        {
            View.Ownerid = per.ToString();
            View.Role = (CRole)proid;
            List<User> list = new List<User>();
            list.AddRange(userDao.GetUserRolesForItems(View.Role, View.Ownerid));// query method call            View.UserListItems.List = list;
            View.UserListItems.TotalRowCount = list.Count;
        }
    }

when i am selecting 1 value then its working fine but for more than one items giving error, I want to know whether its possible with selectedIndexChange or not, if yes how if not then how to do it on one button click


Solution

  • this may help

        foreach (ListItem item in lstbox.Items)
            {
                if (item.Selected)
                {
                   //code here
    
                }
            }