Reputation: 568
I have an ASP table which contains a large number of radio buttons. I want to loop through them all quickly and set the checked property to false:
<asp:Table runat=Server ID=tblSchedule>
<asp:TableRow>
<asp:TableCell>
<asp:RadioButton runat=Server ID=rdb1/>
</asp:TableCell>
</asp:TableRow>
</asp:table>
The following code never returns any results though.
foreach (RadioButton rdb in tblSchedule.Controls.OfType<RadioButton>())
{
rdb.Checked = false;
}
Upvotes: 2
Views: 3634
Reputation: 34846
You need to loop through the layers of the table control, like this:
foreach (var tr in tblSchedule.Controls.OfType<TableRow>())
{
foreach (var td in tr.Controls.OfType<TableCell>())
{
foreach (var rdb in td.Controls.OfType<RadioButton>())
{
rdb.Checked = false;
}
}
}
Or alternatively you can use LINQ, like this:
foreach (var rdb in tblSchedule.Controls.OfType<TableRow>()
.SelectMany(tr => tr.Controls.OfType<TableCell>()
.SelectMany(td => td.Controls.OfType<RadioButton>())))
{
rdb.Checked = false;
}
Upvotes: 1
Reputation: 460118
As far as i remember the table's control cllection does not contain all controls in all rows' cells. Controls.OfType
does not search recursively in child controls. So you either have to use a recursive method or just use the Rows
property and this linq query:
IEnumerale<RadioButton> allRadios = this.tblSchedule.Rows.Cast<TableRow>()
.SelectMany(r => r.Cells.Cast<TableCell>()
.SelectMany(c => c.Controls.OfType<RadioButton>()));
foreach(RadioButton rBtn in allRadios)
rBtn.Checked = false;
Upvotes: 0