Stevie Stevie - 26 days ago 7
C# Question

C# Destroying the effects of a class

I have a public class Puzzle that creates a puzzle of buttons (a 2d array of buttons) and places them in Form1 of my Windows Form Application(It sets Form1 as their Parent). when I call a function to remove all these buttons except for the reset_button, it will delete only half of them. I have to call this method n times in order to get all these buttons deleted, where n x n = the number of buttons my puzzle has.

public void Remove(Form g)
{
for (int i=0; i<n;i++)
foreach (Button b in g.Controls)
{
if (b.Name!="btn_reset") b.Dispose();
}
}


in the Form1 class puzzle is a new instance of the class Puzzle, and Remove is a public method within the class Puzzle

btn_reset.MouseClick += (ss, ee) =>
{
puzzle.Remove(this);
//puzzle=new Puzzle(n,this);
};


Any idea why this happens?

Answer

You are actually not removing the buttons only disposing them. I would suggest this code:

public void Remove(Form g)
{
    var toRemove = g.Controls.OfType<Button>().Where(x => x.Name != "btn_reset").ToList();
    foreach(Button b in toRemove)
    {
        g.Controls.Remove(b);
    }
}

Please note:

  • You have to create a new List of the controls (toRemove in the example) because you cannot directly iterate over Controls and remove items from this list.
  • You have to add using System.Linq;

UPDATE: As stated by other users, dispose also removes controls from its parent. So the actual problem was not the call to Dispose but the way you used the iterator .So you could also use this code

public void Remove(Form g)
{
    var toRemove = g.Controls.OfType<Button>().Where(x => x.Name != "btn_reset").ToList();
    foreach(Button b in toRemove)
    {
        b.Dispose();
    }
}