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

StackOverflow https://stackoverflow.com/questions/11212117

  •  17-06-2021
  •  | 
  •  

Question

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

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top