Search code examples
c#splitcontainer

can not dispose controls in splitcontainer


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.


Solution

  • 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();
     }