Search code examples
c#asp.netcontrolcollection

cannot convert from 'System.Web.UI.ControlCollection' to 'System.Collections.Generic.IEnumerable<System.Web.UI.Control>'


I would like to clear and dispose of all the components inside of an asp:panel. I am receiving the error:

cannot convert from 'System.Web.UI.ControlCollection' to 'System.Collections.Generic.IEnumerable'

Heres my code:

List<Control> ctrls = new List<Control>(panelLayout.Controls);
panelLayout.Controls.Clear();
foreach (Control control in ctrls)
{
   control.Dispose();
}

Any ideas on what I need to change on line: List ctrls = new List(panelLayout.Controls);

Thanks, Larry


Solution

  • You don't have to create a list first. You can iterate on your Controls collection.

    foreach (Control control in panelLayout.Controls)
    {
       control.Dispose();
    }
    panelLayout.Controls.Clear();
    

    You get the error because List<T> expects a IEnumerable<T> in its constructor. Your collection doesn't implement that interface.

    Also you have to clear the collection after you disposed them like jrummell pointed out.