can not dispose controls in splitcontainer

459 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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