Search code examples
c#dynamictextboxparent-childpicturebox

Delete all dynamically created PictureBoxes with the same parent in c#


I am writing a windows forms application in C# in which i am dynamically creating TextBoxes and PictureBoxes with a Panel as the parent:

PictureBox pb = new PictureBox();
pb.Parent = MainPanel;
pb.Name = "pb" + "r" + NumberInRow + "c" + NumberInColumn+ "bi" + buildIndex;
pb.Location = new Point(30 * NumberInRow + 192 * (NumberInRow - 1), 50 * NumberInColumn + 273 * (NumberInColumn - 1));
pb.ImageLocation = ThumbLinks[i];

TextBox tb = new TextBox();
tb.Parent = MainPanel;
tb.Name = "tb" + "r" + NumberInRow + "c" + NumberInColumn + "bi" + buildIndex;
tb.Location = new Point(pb.Location.X - 4, pb.Location.Y + pb.Size.Height + 5);
tb.Text = GalleryNames[i];

I am trying to delete them with this:

foreach (PictureBox pb in MainPanel.Controls)
    {
                MainPanel.Controls.Remove(pb);
    }

foreach (TextBox tb in MainPanel.Controls)
     {
                MainPanel.Controls.Remove(tb);
     }

This only seems to work once though. Visual Studio tells me that it can't convert System.Windows.Forms.TextBox into System.Windows.Forms.PictureBox.

Is there any way to delete the PictureBoxes and TextBoxes differently?

I've read about something like MainPanel.Children.Remove(); but it doesn't seem to exist or i am doing something wrong.


Solution

  • Look at MainPanel.Controls.OfType<PictureBox>() and MainPanel.Controls.OfType<TextBox>(). You can use this in conjunction with a .ToList() call to avoid modifying an interator while it's still active:

    var PBs = MainPanel.Controls.OfType<PictureBox>().ToList();
    var TBs = MainPanel.Controls.OfType<TextBox>().ToList();
    foreach (var pb in PBs)
    {
        MainPanel.Controls.Remove(pb);
    }
    foreach (TextBox tb in TBs)
    {
        MainPanel.Controls.Remove(tb);
    }