遍历GridView中的所有行 [英] iterate through ALL rows in a GridView
本文介绍了遍历GridView中的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
较低的代码可以正常工作,但是有一个错误:
elow code works fine but there is a bug :
如果Employee对象返回了5行,而我试图根据ID选中该复选框,但它仅与最后一个ID匹配-它应该检查所有5行..
if Employee object has return 5 rows and i am trying to checked the check box based on the ids but instead its just matching only the last id - it suppose to checked all 5 rows..
List<Employee> result = new List<Employee>();
long Id = (long)Session["Id"];
result = Employee.GetEmployeeById(Id);
foreach (GridViewRow row in gv.Rows)
{
CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
if (c != null)
{
if (result.Count > 0)
{
foreach (Employee item in result)
{
Label Id = row.FindControl("lblId") as Label;
if (Id.Text == item.Id.ToString())
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
推荐答案
看看您的逻辑-您只有一个复选框.您正在取消选中并检查员工循环中的同一控件.每个网格行是否都有一个复选框,该复选框应根据ID在员工列表中存在的条件来选择?
Look at your logic - you only have the one checkbox. You're unchecking and checking the same control in the employee loop. Does each grid row have a checkbox that should be selected based on the condition the id exists in the employee list?
foreach (GridViewRow row in gv.Rows)
{
Label Id = row.FindControl("lblId") as Label;
var result = Employee.GetEmployeeById(Id.Text);
if (result.Count > 0)
{
CheckBox chkBox = row.FindControl("chkSelected") as CheckBox;
if (chkBox != null)
{
chkBox.Checked = result.Any(x => x.Id.ToString() == Id.Text);
}
}
}
这篇关于遍历GridView中的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文