Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem with foreach (Control loop 2

Status
Not open for further replies.

James1981

Programmer
Nov 2, 2002
76
0
0
US
Hi I've got the following loop:

Code:
foreach (DropDownList ddl in myPanel.Controls)
{
   ddl.ClearSelection();
}

I keep on getting a cast error, saying that it can't cast to DropDownList. I know there are DropDownList controls within the panel I am looping thru, as I have debugged and seen them in the code watch.

Any ideas?

James.
 
Code:
foreach(Control ctrl in Page.Controls)
{							
 if(ctrl.GetType().ToString() == "System.Web.UI.HtmlControls.HtmlForm")
 {
   HtmlForm parent = (HtmlForm)ctrl;
   foreach(Control c in parent.Controls)
   {
    if(c.GetType().ToString()== "System.Web.UI.WebControls.DropDownList")
    {						  
      ((DropDownList)c).Items.Clear();
    }
   }
   break;
  }
}
 
Maybe even less code:

<form id=myForm method=post runat=&quot;server&quot;>

HtmlForm form = (HtmlForm)Page.FindControl(&quot;myForm&quot;);
foreach(Control c in form.Controls)
{
if(c.GetType().ToString() == &quot;System.Web.UI.WebControls.DropDownList&quot;)
{
((DropDownList)c).Items.Clear();
}
}
 
The problem is that you are dealing with a Controls Collection, not a DropDownList Collection.

Try this:

1. Loop through each Control in myPanel.Controls
2. Check to see if the control is a DropDownList, if it is, then do the processing.

In other words, check out what LV is doing, but do it for your Panel instead of the form.
 
Yep, BoulderBum is right - thought about Page for some reason.
Code:
foreach(Control c in myPanel.Controls)
{
 if(c.GetType().ToString() == &quot;System.Web.UI.WebControls.DropDownList&quot;)
 {
 ((DropDownList)c).Items.Clear();
 }
}
 
Thanks people - your feedback is excellent.

The key was what type of collection it was - a control collection not a DropDownList collection.

Thanks again,

James
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top