Ref:
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<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*=lstHobbies]').multiselect({
includeSelectAllOption: true
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="lstHobbies" runat="server" SelectionMode="Multiple"></asp:ListBox>
<asp:Button ID="Button1" Text="UpdateHobbies" runat="server" OnClick="UpdateHobbies" />
</div>
</form>
</body>
</html>
Namespaces
using System.Data.SqlClient;
using System.Configuration;
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.PopulateHobbies();
}
}
private void PopulateHobbies()
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select * from hobbies";
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
ListItem item = new ListItem();
item.Text = sdr["Hobby"].ToString();
item.Value = sdr["HobbyId"].ToString();
item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
lstHobbies.Items.Add(item);
}
}
conn.Close();
}
}
}
protected void UpdateHobbies(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["constr"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "update hobbies set IsSelected = @IsSelected" +
" where HobbyId=@HobbyId";
cmd.Connection = conn;
conn.Open();
foreach (ListItem item in lstHobbies.Items)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@IsSelected", item.Selected);
cmd.Parameters.AddWithValue("@HobbyId", item.Value);
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}
SQL
Please download the Sql file from Second link.
Screenshots
Database saved values