Skip to content Skip to sidebar Skip to footer

Asp.net Looping Through Table

I was wondering if any one could help me out; I have a table which looks something like the following:

Solution 1:

If you want to access the rows in ASP.NET (on the server side), you need to convert the table, rows and the cells to server control (using runat="server") and iterate through the controls in the table.

EDIT : :- If you are adding the rows, cells and radionbuttons following way, all of them will be the server controls (and are runat=server) so that you can access them the way I mentioned above:--

// Create new row and add it to the table.TableRowtRow=newTableRow();
table1.Rows.Add(tRow);
for (cellCtr = 1; cellCtr <= cellCnt; cellCtr++)
{
// Create a new cell and add it to the row.   TableCelltCell=newTableCell();
RadioButtonrdb=newRadioButton();
rdb.ID = "rdb_" + cellCtr.ToString();
rdb.Text = "radio button";
rdb.GroupName = "rdbGroup";
tCell.Controls.Add(rdb);
tRow.Cells.Add(tCell);
}

EDIT:-

You can find the controls in each cell.Something like below:-

foreach(TableCell cell in tableRow.Cells)
{
      foreach(Control ctrl in cell.Controls)
      {
      if(ctrl is RadioButton)
      {
         if(ctrl.Selected)
          {
             string rdValue=ctrl.Text;
          }
      }
      }

}

Or If you want to iterate on the client side using Javascript, have a look here and you dont have to apply runat="server".

Solution 2:

It sounds like you're starting with a barebones <table> in your markup page, and dynamically adding those <input> afterwards.

Consider taking this approach:

  1. Add the runat="server" attribute to your table.
  2. In the code where you're adding those <input> tags, add a new RadioButton control. Use an ID here that you can predict later. Perhaps you can use a RadioButtonList instead, if the choices are logically grouped!
  3. It's unclear if you're manually adding those <tr> and <td> as strings. Consider the option of new TableRow() and new TableCell(). Then add the new RadioButton to the TableCell.Controls collection with tc.Controls.Add(myNewRadioButton);
  4. In your postback code, simply refer to your RadioButton controls by id, or even loop through the Controls collection property of the Table1.
foreach (Control x in Table1.Controls)
{
    if (x.GetType().ToString().Equals("System.Web.UI.WebControls.RadioButton"))
    {
         if (((RadioButton)x).Checked)
         {
             //proceed.
         }
    }
}

Solution 3:

Convert all controls to server controls (by adding the runat="server" attribute). You can then programatically access what you need o. The server.

Post a Comment for "Asp.net Looping Through Table"