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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

            }
        }

    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x