asp.netdropdownlistfor

asp Dropdownlist multiple item selection


I'm trying to select multiple items from a drowpdownlist, I'm using bootstrap, but my problem: I can just get only the first selected item, cannot get others selected ones.

my code (styles and scripts):

 <link rel="stylesheet" href="Content/bootstrap.min.css" /> <!-- Bootstrap v4.4.1 -->
 <link rel="stylesheet" href="Content/bootstrap-select.css" /> <!-- Bootstrap-select v1.13.1 -->
 <script src="js/jquery-1.9.1.js"></script>
 <script src="Scripts/bootstrap.bundle.min.js"></script>
 <script src="Scripts/bootstrap-select.min.js"></script> <!-- Bootstrap-select v1.13.1  -->
 <script type="text/javascript">
    $('select').selectpicker();
 </script>

my DDL:

<asp:DropDownList CssClass="selectpicker" ID="DropDownList1" runat="server" multiple data-live-search="true"  SelectionMode="multiple">
            <asp:ListItem>Brasil</asp:ListItem>
            <asp:ListItem>Colombia</asp:ListItem>
            <asp:ListItem>United States</asp:ListItem>
            <asp:ListItem>Frannce</asp:ListItem>
            <asp:ListItem>Italy</asp:ListItem>
            <asp:ListItem>Japan</asp:ListItem>
        </asp:DropDownList>

I use a button and this is OnClick command:

protected void btnSend_Click(object sender, EventArgs e)
{
    string selectedItems = "";
    foreach (ListItem item in DropDownList1.Items)
    {
        if (item.Selected)
        {
            selectedItems += item.Text + "\\n";
        }
    }
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + selectedItems + "');", true);
}

As I said.. I can get only the first item, anyone please can help me? thanks

best regards


Solution

  • The DropDownList

    allows the user to select a single item from a drop-down list

    A ListBox allows you to select multiple items:

    <asp:ListBox CssClass="selectpicker" 
                 ID="DropDownList1" 
                 runat="server" 
                 data-live-search="true"  
                 SelectionMode="Multiple">
        <asp:ListItem>Brasil</asp:ListItem>
        <asp:ListItem>Colombia</asp:ListItem>
        <asp:ListItem>United States</asp:ListItem>
        <asp:ListItem>Frannce</asp:ListItem>
        <asp:ListItem>Italy</asp:ListItem>
        <asp:ListItem>Japan</asp:ListItem>
    </asp:ListBox>
    

    The rest of your code should work as is, maybe update the ID. Aspsnippets have an example using bootstrap.