迭代GridView中的所有行

时间:2011-07-20 03:45:41

标签: asp.net gridview

 <asp:TemplateField HeaderText="Select">
 <ItemTemplate>
 <asp:CheckBox ID="chkSelected" runat="server" Checked="false"></asp:CheckBox>
  </ItemTemplate>
 </asp:TemplateField>

elow代码工作正常,但有一个错误:

如果Employee对象返回5行,我试图根据id检查复选框,而只是只匹配最后一个id - 它假设检查了所有5行..

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;
             }
           }
       }

1 个答案:

答案 0 :(得分:5)

看看你的逻辑 - 你只有一个复选框。您正在取消选中并检查员工循环中的同一控件。每个网格行是否都有一个复选框,应该根据员工列表中id的条件来选择?

 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);

            }
        }

    }