Foreach control item in panel not selecting all items

My problem is that i've got a panel called PanelNewFriend, where i'm dynamically creating buttons from all users from a mysql database. So when someone clicks on a user and sends an invite , what should be happening is that it should remove all buttons (Except for the back button which has a tag of "1") and then place all the buttons again for the new list of all users.

When creating the buttons i assigned a tag with value "0" to them. All buttons have it even though i don't think the problem lies in the tag.

I'm using this code to remove all buttons in the panel.

foreach (Button item in PanelNewFriend.Controls.OfType<Button>())
        {
            if (item.Tag == "0")
            {
                PanelNewFriend.Controls.Remove(item);
            }
        }

I've tried multiple things, ranging from foreach Control item and oftype Control. To changing the item.Tag != "1" and item.Tag == "". None of this worked

But when i actually execute the code and add breaking points I can see that there are 4 buttons in the panel. But when i go through each foreach cycle, it only selects 2 of the 4 buttons. So since it only selects 2 buttons it is only deleting 2 and leaving the other 2 alone.

Any idea what could be causing this and how to fix it?


Classic collection modification problem here. You're modifying the collection as you're iterating over it. That will result in unexpected behavior. Ideally you should be getting InvalidOperationException but sadly ControlCollection doesn't implement this check.

You have two options. Either take a copy of the collection and iterate over the copy or use a reverse for loop.

var buttonsToRemove = PanelNewFriend.Controls
                                .OfType<Button>()
                                .Where(x=> x.Tag == "0")
                                .ToArray();//Take a copy

foreach (Button item in buttonsToRemove)
{
    PanelNewFriend.Controls.Remove(item);
}

像这样尝试

List<Button> removeList = new List<Button>();
foreach (Button item in PanelNewFriend.Controls.OfType<Button>())
{
  if (item.Tag == "0")
  {
    removeList.Add(item);
  }
}
foreach (Button item in removeList)
  PanelNewFriend.Controls.Remove(item);
链接地址: http://www.djcxy.com/p/61568.html

上一篇: 如何防止控件绑定到面板

下一篇: 面板中的Foreach控制项目不选择所有项目