foreach with dropdownlists

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
I have some dropdownlist web controls on as aspx page. I want to loop
through them on first (!IsPostBack) Page_Load in order to populate them. The
foreach control structure seems to be a good condidate for this though I'm
having problems getting the right syntax/form. I've been trying variations on
the following:

foreach (DropDownList myDDL in Controls)
{
//do something here
}

Can anyone give me an indication of what I maight be doing wrong?

many thanks,

Pete
 
Italian said:
I have some dropdownlist web controls on as aspx page. I want to loop
through them on first (!IsPostBack) Page_Load in order to populate them. The
foreach control structure seems to be a good condidate for this though I'm
having problems getting the right syntax/form. I've been trying variations on
the following:

foreach (DropDownList myDDL in Controls)
{
//do something here
}

Can anyone give me an indication of what I maight be doing wrong?

The above will fail if any controls are *not* DropDownLists. You need:

foreach (Control control in Controls)
{
Control ddl = control as DropDownList;
if (ddl != null)
{
// Do something here
}
}
 
Hi,

Beside jon's sugestion I would find really weird that you do not know
beforehand how many dropdown you have, or the name of them, if you do know
this and your datasource support IList (arraylist, datatable, array, etc )
you can use binding.


cheers,
 
Back
Top