Hi Chriz,
I have created sample code which fullfill your requirement.
HTML
<div>
<asp:Panel ID="pnlUser" runat="server">
<asp:CheckBoxList ID="chkUsers" runat="server">
</asp:CheckBoxList>
</asp:Panel>
<asp:Button ID="btnUpdate" OnClick="OnUpdate" Text="Update" runat="server" />
</div>
C#
private string constring = ConfigurationManager.ConnectionStrings["Constring"].ToString();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.PopulatesUsersName();
}
}
private void PopulatesUsersName()
{
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Category", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
ViewState["Data"] = dt;
chkUsers.DataSource = dt;
chkUsers.DataTextField = "Category";
chkUsers.DataValueField = "UserName";
chkUsers.DataBind();
CheckboxsItems();
}
}
}
}
private void CheckboxsItems()
{
foreach (ListItem item in chkUsers.Items)
{
string values = item.Value.ToString();
foreach (DataRow row in dt.Rows)
{
string id = row["UserName"].ToString();
string status = row["Status"].ToString();
if (values == id && status.ToUpper() == "TRUE")
{
item.Selected = true;
}
}
}
}
protected void OnUpdate(object sender, EventArgs e)
{
foreach (ListItem item in chkUsers.Items)
{
if (item.Selected)
{
string id = item.Value.ToString();
Update(id, "TRUE");
}
else
{
DataTable dt = (DataTable)ViewState["Data"];
string id = item.Value.ToString();
foreach (DataRow row in dt.Rows)
{
string values = row["UserName"].ToString();
string status = row["Status"].ToString();
if (values == id && status.ToUpper() != "")
{
Update(id, "FALSE");
}
else if (values == id && status.ToUpper() == "")
{
Update(id, DBNull.Value.ToString());
}
}
}
}
}
private void Update(string id, string status)
{
string constring = ConfigurationManager.ConnectionStrings["Constring"].ToString();
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("Update Category SET Status=@Status WHERE UserName='" + id + "'", con))
{
cmd.Parameters.AddWithValue("@Status", status);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Screenshot