Hey

I have a button that when clicked add some pictureboxes and labels on a panel named "hold"

Now when I change some values and reclick this button I need the old controls to be removed before drawing new ones.

So I added this code at the start of the button when its clicked

foreach (Control c in hold.Controls)
        {
            hold.Controls.Remove(c);
        }

That didnt work so I tried this

for (int i = 0; i < hold.Controls.Count; i++)
        {
            hold.Controls.RemoveAt(i);
        }

That also didnt work, the old labels and pictureboxes sit there on the screen and when the new ones are draw on, it messes up the images.

Funny enough these loops work "kinda" work when I place them after the controls are drawn (at the end of the button click) and removes some of the controls, which is what I expect it to, but why only some? and why not work at start of button click?

Recommended Answers

All 5 Replies

So you only have to remove pictureBoxes, and lables? All of them?
Because you have to be very specific which controls to remove.

I want to remove all controls on the hold panel, when the button outside the panel is clicked.

YOu can do it this way:

List<Label> labels = new List<Label>();
            List<TextBox> textBoxes = new List<TextBox>();
            foreach (Control c in this.Controls)
            {
                if (c is Label)
                {
                    Label label = c as Label;
                    labels.Add(label);
                }
                else if (c is TextBox)
                {
                    TextBox text = c as TextBox;
                    textBoxes.Add(text);
                }
            }

            foreach (Label l in labels)
                this.Controls.Remove(l);
            foreach (TextBox t in textBoxes)
                this.Controls.Remove(t);

Fixed it

I had to use this loop

 for (int i = hold.Controls.Count - 1; i > -1; i--)
        {
            hold.Controls.RemoveAt(i);
        }

Ok, glad to hear. Though you can try out code I gave you.
if the issue is salved, you can close the thread (mark it as answered).
best regards

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.