[英]update database on checkbox change in gridview asp.net c#
I have a CheckBox in GridView cell. 我在GridView单元格中有一个CheckBox。 I want to update the database on CheckBox change, like when I unchecked it, 'Status' column in table update as false or vice versa. 我想在CheckBox更新时更新数据库,就像我取消选中它时,表中的'Status'列更新为false,反之亦然。
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. 假设您希望在Checked
状态更改后立即更新(用户单击CheckBox
),则必须先设置AutoPostBack="true"
。
Then you can handle the CheckBox.CheckedChanged
event: 然后你可以处理CheckBox.CheckedChanged
事件:
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 C#代码
protected void chkview_CheckedChanged(object sender, EventArgs e)
{
// code here.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.