0

I created some user controls that I place on a form programmatically in VS 2013. Those controls need to be deleted and recreated on occasion. I have tried deleting the controls two different ways. One works, one doesn't. I'm hoping someone can provide insight as to why the one does not work.

This version does NOT work (it only finds two out of four controls):

// delete user controls from the front panel
foreach (UserControl ctrl in this.Controls.OfType<StationControl>())
{
    this.Controls.Remove(ctrl);
}

This version does work (it finds four out of four controls):

// delete user controls from the front panel
var uc_list = this.Controls.OfType<StationControl>().ToArray();
foreach (var ctrl in uc_list)
{
    this.Controls.Remove(ctrl);
}

I can count the number of user controls matching the type without issue (e.g.

int controlCount = this.Controls.OfType<StationControl>().Count()

So why does the first foreach statement not fully work?

manjagu
  • 3
  • 2
  • 2
    Because, in the first example, you are removing controls from the same collection where you are looping over. In the second one you loop over a different collection and remove from the form controls collection – Steve Jul 29 '16 at 20:44
  • Possible duplicate of [Efficiently deleting item from within 'foreach'](http://stackoverflow.com/questions/8791557/efficiently-deleting-item-from-within-foreach) – Frank Tan Jul 29 '16 at 20:46

1 Answers1

0

Will this work?

foreach (UserControl ctrl in this.Controls.OfType<StationControl>())
{
    ctrl.Dispose();
    this.Controls.Remove(ctrl);
}

I hope this helps.

Edit:

The above won't work properly, here is a working approach:

while (this.Controls.OfType<StationControl>().Count() > 0)
{
    UserControl ctrl = this.Controls.OfType<StationControl>().First();

    ctrl.Dispose();
    this.Controls.Remove(ctrl);
}
MasterXD
  • 804
  • 1
  • 11
  • 18