Julian
Julian

Reputation: 23

Delete dynamically generated CheckBoxes in C#

I am generating dynamically Checkbox-buttons on a panel according to my SQL data. I created a button to "refresh" my buttons, I mean I delete / update buttons. My problem is I cannot delete the old buttons. After a created the buttons I am trying to delete a specific one:

foreach (CheckBox item in panel.Controls.OfType<CheckBox>())
{
    panel.Controls.Remove(item);
} 

There are only a few deleted. Any suggestion?

Upvotes: 2

Views: 491

Answers (1)

Stephen Duffy
Stephen Duffy

Reputation: 71

Make the list of the controls to delete before deleting them. You’re trying to delete items from the collection you’re iterating over, which can be problematic.

Upvotes: 2

Related Questions