I have a CheckBox in GridView cell. I want to update the database on CheckBox change, like when I unchecked it, 'Status' column in table update as false or vice versa.
Your question is very incomplete. But i'll give it a try, maybe it's helpful anyway.
Assuming you want to update as soon as the Checked
state has changed(the user clicked the CheckBox
), you have to set AutoPostBack="true"
first.
Then you can handle the CheckBox.CheckedChanged
event:
protected void Check_Clicked(Object sender, EventArgs e)
{
// get the checkbox reference
CheckBox chk = (CheckBox)sender;
// get the GridViewRow reference
GridViewRow row = (GridViewRow) chk.NamingContainer;
// assuming the primary key value is stored in a hiddenfield with ID="HiddenID"
HiddenField hiddenID = (HiddenField) row.FindControl("HiddenID");
string sql = "UPDATE dbo.Table SET Status=@Status WHERE idColumn=@ID";
using (var con = new SqlConnection(connectionString))
using (var updateCommand = new SqlCommand(sql, con))
{
updateCommand.Parameters.AddWithValue("@ID", int.Parse(hiddenID.Value));
// assuming the type of the column is bit(boolean)
updateCommand.Parameters.AddWithValue("@Status", chk.Checked);
con.Open();
int updated = updateCommand.ExecuteNonQuery();
}
}
Grid source
<asp:TemplateField HeaderText="View">
<ItemTemplate>
<asp:CheckBox ID="chkview" runat="server" AutoPostBack="true" OnCheckedChanged="chkview_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
C# code
protected void chkview_CheckedChanged(object sender, EventArgs e)
{
// code here.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With