1

i try to dispose controls in split container using this code.

 foreach (Control c in splitContainerMain.Panel2.Controls) 
 { 
     c.Dispose(); 
 }

but problem is split container has contains two controls and get count is two. but i try to dispose using this code then one control is dispose successfully but second control can not be disposed.

Oskar Kjellin
  • 21,280
  • 10
  • 54
  • 93
  • 3
    Is there a reason why you are manually disposing the controls contained within the container instead of just calling `Dispose()` on the container itself? – Samuel Slade Nov 24 '11 at 11:01

1 Answers1

2

I don't think that you should be using foreach in this case since the controls collection could be shrinking as items are disposed.

I think you would be much better off as follows:

 for (int nI = splitContainerMain.Panel2.Controls.Count - 1; nI >= 0; nI--) 
 { 
     splitContainerMain.Panel2.Controls[nI].Dispose();
 }
competent_tech
  • 44,465
  • 11
  • 90
  • 113