[英]Run an event when Checkbox is Checked/Unchecked Gridview C#
I have a Gridview that has 4 columns. 我有一个具有4列的Gridview。 All in
ItemTemplate
One column is a CheckBox. ItemTemplate
所有内容一栏是一个CheckBox。 This Gridview is binded to a datasource. 此Gridview绑定到数据源。 What I want to do is when the Checkbox is checked update the database with the bit value '1' and if I uncheck the Checkbox to do the same but '0'.
我想做的是选中“复选框”时,用位值“ 1”更新数据库,如果我取消选中“复选框”,则执行相同的操作,但“ 0”。
I already know my SQL code to update the database, but I am not sure how to run the event so that it looks at the current row the checkbox is on in the gridview. 我已经知道我的SQL代码来更新数据库,但是我不确定如何运行该事件,以使其查看gridview中复选框所位于的当前行。
Here is the CheckBox Column. 这是CheckBox列。
<asp:TemplateField HeaderText="Pick" ItemStyle-CssClass="hrGrid" HeaderStyle-CssClass="hdrHrBase">
<ItemTemplate>
<asp:CheckBox id="cbViewCustomer" runat="server" OnCheckedChanged="ViewCustomer" onAutoPostBack="true" Checked='<%#(Eval("chosen"))%>'/>
</ItemTemplate>
</asp:TemplateField>
Do I use EventArgs like this: The problem with this is it updates the database but all the rows. 我是否像这样使用EventArgs:问题是它会更新数据库,但会更新所有行。 What I am trying to do is update only the current row that is in the Gridview.
我想做的是仅更新Gridview中的当前行。 I am just not sure where to go from here.
我只是不确定从这里去哪里。
protected void ViewCustomer(object sender, EventArgs e)
{
string SelectCustomer = "UPDATE tblcustomer Set chosen ='0'";
NpgsqlCommand changedata = new NpgsqlCommand(SelectCustomer, con);
con.Open();
changedata.ExecuteNonQuery();
con.Close();
}
Or should I be doing something different? 还是我应该做些不同的事情?
You can do this with OnRowCommand
event of gridview like this:- 您可以使用gridview的
OnRowCommand
事件来做到这一点:-
Associate a RowCommand event with your gridview:- 将RowCommand事件与您的gridview关联:
<asp:GridView ID="mygridview" runat="server" OnRowCommand="mygridview_OnRowCommand">
Next, associate a CommandName
& CommandArgument
to your checkbox:- 接下来,将
CommandName
和CommandArgument
关联到您的复选框:
<asp:TemplateField HeaderText="Pick" ItemStyle-CssClass="hrGrid" >
<ItemTemplate>
<asp:CheckBox id="cbViewCustomer" runat="server" Checked='<%#(Eval("chosen"))%>'
CommandName="myCheckbox" CommandArgument="<%# Container.DataItemIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
In the code behind handle the event:- 在处理事件的代码中:
protected mygridview_OnRowCommand (object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "myCheckbox")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow row = mygridview.Rows[rowIndex];
bool ischecked = (row.FindControl("cbViewCustomer") as CheckBox).Checked;
}
}
You can also do it with checbox checked event, but if you have multiple controls then fire the gridview command event instead of individual events. 您也可以使用checbox选中的事件来执行此操作,但是如果您有多个控件,则触发gridview命令事件而不是单个事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.