3

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?

Ishan
  • 4,008
  • 32
  • 90
  • 153
  • How do you create checkboxes? In aspx or in RowCreated / RowDatabound event? grdApproverDetails.Rows[i].Controls of `CheckBox` type can be a solution? – Emanuele Jul 31 '17 at 08:03
  • @Emanuele This is how i am creating the `CheckBox` https://stackoverflow.com/questions/45333248/how-to-create-dynamic-checkboxes-inside-a-gridview/45344818#45344818 – Ishan Jul 31 '17 at 08:06

2 Answers2

0

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)
               //...
           }
       }
    }
}
Emanuele
  • 648
  • 12
  • 33
  • This doesnt return any of the controls inside the grid. – Ishan Aug 01 '17 at 07:11
  • I edited my post. I showed a solution then it depends from table structure. You can edit it: `row.Cells`, `row.Cells[k].Controls`, recursion on container control and so on. – Emanuele Aug 01 '17 at 07:34
0

I got it working thanks to Emanuele

foreach (GridViewRow row in grdApproverDetails.Rows)
{
     List<CheckBox> listCkb = new List<CheckBox>();

     ControlCollection cntrColl=  row.Cells[2].Controls;
     foreach (Control cntr in cntrColl)
     {
         if (cntr is CheckBox && cntr.ID.Contains("approvernamesdynamic_"))
         {

         }
      }
}
Ishan
  • 4,008
  • 32
  • 90
  • 153