foreach with dropdownlists

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
 
J

Jon Skeet [C# MVP]

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
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top