asp.net gridview复选框选择 [英] asp.net gridview checkbox selection
问题描述
需要一些帮助来解决这个问题.
Need some help to solve this.
我有一个 gridview,在 gridview 中有一个复选框,单击该复选框后,我正在执行回发事件并尝试仅在数据库上更新此特定行.
I have a gridview and inside the gridview I have a checkbox and after clicking the checkbox, I am doing a postback event and trying to update this particular row only on the database.
这是我的 gridview 复选框代码.请参阅 OnCheckedChanged.
This is my gridview checkbox code. see the OnCheckedChanged.
<asp:TemplateField HeaderText="Sample">
<ItemTemplate>
<asp:CheckBox runat="server"
ID="chkSample"
Checked='<%# Bind("Sample") %>'
OnCheckedChanged="UpdateSupplyLed"
AutoPostBack="True">
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
代码:
protected void UpdateSupplyLed(object sender, EventArgs e)
{
foreach (GridViewRow di in SamplingGridView.Rows)
{
CheckBox chkBx = (CheckBox)di.FindControl("chkSample");
if (chkBx != null && chkBx.Checked)
{
//update database logic here.
}
}
}
上面的代码工作正常,但它让我选中了所有选中的复选框,而与我刚刚选中的复选框无关.我不想要所有的.
The above code works fine but it is getting me all the checkboxes that are checked irresepective of the one that I just checked. I don't want all of them.
如何获取刚刚检查的唯一一行值.某些行可能已被检查,因为这些记录的状态为 true,我不想更新这些记录.
How can I get the only one row value that have been just checked. Some of the rows might have been checked already because the status is true for those records and I don't want to update those records.
我想我的问题是对的!
更新:答案是:
protected void UpdateSupplyLed(object sender, EventArgs e)
{
CheckBox chkSampleStatus = sender as CheckBox;
bool sample = chkSampleStatus.Checked;
GridViewRow row = chkSampleStatus.NamingContainer as GridViewRow;
TextBox txtId = row.FindControl("Id") as TextBox;
int id = Int32.Parse(txtId.Text);
}
推荐答案
试试这个:
CheckBox chkBx = sender as CheckBox;
而不是迭代所有行.
我自己没有以这种方式在 GridView 中使用 CheckBox.通常我会使用 GridView 的 OnRowCommand 事件,并使用 RowIndex 或 CommandArgument 值来更新数据库.
I haven't used CheckBox's in a GridView in this way myself. Usually I would use the GridView's OnRowCommand event instead and use the RowIndex or CommandArgument value to update the database.
考虑到 OnRowcommand 可能很难触发 CheckBox,更好的解决方案可能是坚持使用复选框的 CheckChanged 事件并使用控件 NamingContainer 导航到 GridViewRow 服务器端.类似的东西:
Thinking about it OnRowcommand could be tricky for a CheckBox to fire, a better solution might be sticking with the CheckChanged event of the checkbox and navigate up to the GridViewRow serverside using controls NamingContainer. Something like:
GridViewRow row = chkBx.NamingContainer as GridViewRow;
我假设 CheckBox => Cell => Row 如果您使用 Google ASP.NET NamingContainer,您将获得更多细节.
I'm assuming the goes CheckBox => Cell => Row if you Google ASP.NET NamingContainer you'll get some more specifics.
这篇关于asp.net gridview复选框选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!