Saving and retrive multiple selected values of Bootstrap DropDownList using C# in ASP.Net

Last Reply on Nov 03, 2016 05:30 AM By Indresh

Posted on Nov 02, 2016 01:55 AM

How i can save and retrive multiple values from dropdown list

Posted on Nov 02, 2016 02:01 AM Modified on on Nov 02, 2016 03:42 AM

Hi rameshsu,

I have created sample code which fullfill your requirement using the below article.

Bootstrap style DropDownList example in ASP.Net

HTML

<form id="form1" runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
    rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css"
    rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js"
    type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('[id*=lstFruits]').multiselect({
            includeSelectAllOption: true
        });
    });
</script>
<asp:ListBox ID="lstFruits" runat="server" SelectionMode="Multiple">
    <asp:ListItem Text="Mango" Value="1" />
    <asp:ListItem Text="Apple" Value="2" />
    <asp:ListItem Text="Banana" Value="3" />
    <asp:ListItem Text="Guava" Value="4" />
    <asp:ListItem Text="Orange" Value="5" />
</asp:ListBox>
<asp:Button Text="Save" runat="server" OnClick="Submit" />
<asp:Button ID="btnRetrive" Text="Retrive" runat="server" OnClick="Retrive" />
</form>

C#

protected void Retrive(object sender, EventArgs e)
{
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT  * FROM Fruit", con))
        {
            con.Open();
            SqlDataReader idr = cmd.ExecuteReader();
            while (idr.Read())
            {
                foreach (ListItem item in lstFruits.Items)
                {
                    if (item.Value == idr["FruitId"].ToString())
                    {
                        item.Selected = true;
                    }
                }
            }
        }
        con.Close();
    }
}

protected void Submit(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(constr);
    foreach (ListItem item in lstFruits.Items)
    {
        if (item.Selected)
        {
            SqlCommand cmd = new SqlCommand("INSERT INTO Fruit VALUES(@FruitId,@Name)", con);
            cmd.Parameters.AddWithValue("@FruitId", item.Value);
            cmd.Parameters.AddWithValue("@Name", item.Text);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

Screenshot