Friday, March 16, 2012

looping through table controls

I have an asp:Table control which I dynamically add rows, cells and drop down lists. What I need some help figuring out is how can I loop through the table rows that get added and retrieve the values from the drop down lists that may have been selected.

Thanks in advance for any help.

Here is what I have so far:

foreach(TableRow tr in tblSortOptions)
{

string selectedValue = ((CheckBox)tr.FindControl("ddlSort")).Selected.Item.Value;

}Here's a key part. If you are going to use FindControl, you must specify unique ID property values for all controls in the "naming container". That means each DropDownList gets a unique ID value. Not so convenient when you want the loop above.

Instead, if your rows have the same structure for TableCells, you can retrieve the correct cell by its index. Similarly for retreiving the DropDownList. Suppose the DropDownList is control number 1 (index=0) in table cell 3 (index=2).

foreach(TableRow tr in tblSortOptions)
{
TableCell td = tr.Cells[2];
DropDownList ddl = (DropDownList) td.Controls[0];
string selectedValue = ddl.Selected.Item.Value;

}

0 comments:

Post a Comment