0

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?

Edited by Reverend Jim: Fixed formatting

2
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by Mitja Bonca
0

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

0

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

0

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);
0

Fixed it

I had to use this loop

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

Edited by Reverend Jim: Fixed formatting

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.