开发者

iterate through ALL rows in a 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 :

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


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

            }
        }

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜