Search code examples
c#asp.netgridviewfindcontrol

How to get all the controls inside a specific cell in a GridView


I am generating CheckBox controls dynamically inside a GridView. Now i need to validate if atleast one CheckBox is selected and also while saving data i need to iterate through all the controls inside the cell.

Now the issue is i cannot do grdApproverDetails.Rows[i].FindControl('controlID'), because the ID's are dynamically generated based on the control count. As shown in this thread.

This is how the GridView looks and Approver Name is the column inside which i need to find controls, if CheckBoxes. enter image description here

How can i get all the controls inside a GridView cell and iterate through?


Solution

  • You can get checkboxes using (handwritten code):

    foreach (GridViewRow row in grdApproverDetails.Rows)
    {
        for (int k = 0; k < row.Cells.Count; k++)
        {
           for (int i = 0; i < row.Cells[k].Controls.Count; i++)
           {
               Control control = row.Cells[k].Controls[i];
               if(control is CheckBox)
               {
                   CheckBox chk = control as CheckBox;
                   if(chk != null && chk.Checked)
                   //...
               }
           }
        }
    }