本文介绍了遍历 GridView 中的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
限时送ChatGPT账号.. <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屋!
更多推荐
[db:关键词]
发布评论