0

I am trying to loop through every control in a panel and clear out all the contents if it is a DropDownList.

Here is what I have :

private void ClearOut()
{
    foreach (Control list in MainPanel.Controls)
    {
        if (list.ToString().Equals("System.Web.UI.WebControls.DropDownList"))
        {
            //Clear it out here
        }
    }
}

This code does find every DropDownList, but then I cannot figure out how to clear them out once I get there. I can't use any properties of a DropDownList like selectedindex or items.clear().

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Jason Renaldo
  • 2,802
  • 3
  • 37
  • 48

2 Answers2

2
using System.Linq;
using System.Web.UI.WebControls;

foreach (DropDownList list in MainPanel.Controls.OfType<DropDownList>())
{
    list.Items.Clear();
}

or the same but manually:

foreach (Control c in MainPanel.Controls)
{
    DropDownList list = c as DropDownList;
    if (list != null)
    {
        list.Items.Clear();
    }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
1

Use this:

if(list is DropDownList)
{
DropDownList DDL = list as DropDownList;
DDL.Items.Clear();
}
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
  • [Still it's better to do not mix operators `as` and `is`](http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr) – abatishchev Apr 09 '13 at 18:13