Search code examples
c#dynamic-arrays

Remove buttons from dynamic array


Before I generate buttons in my program, it's supposed to clear them using:

for (int i = 0; i < buttons.Length; i++)
    this.Controls.Remove(buttons[i]);

However all the buttons from the previous generation remain. What might be causing this?

(Below is the entire function, numButton changes in other functions.)

    int numButtons = 5;
    Button[] buttons = new Button[10];

    private void generate_buttons()
    {
        for (int i = 0; i < buttons.Length; i++)
        {
            this.Controls.Remove(buttons[i]);
        }
        for (int i = 0; i < numButtons; i++)
        {
            buttons[i] = new Button();
            buttons[i].Name = "btn" + i.ToString();
            buttons[i].Text = Convert.ToString(i + 1);
            buttons[i].Size = new Size(40, 24);

            int yOffset = 40;
            int xOffset = 20 + i * 42;
            buttons[i].Location = new Point(xOffset, yOffset);
            buttons[i].BackColor = System.Drawing.SystemColors.Control;
            buttons[i].Enabled = false;
            buttons[i].Click += new EventHandler(this.clickMe);
            buttons[i].Visible = true;
            this.Height = yOffset + 104;
            this.Width = xOffset + 75;
        }
        Controls.AddRange(buttons);
    }

Solution

  • Although you're removing the buttons from the control collection, you're not removing it from your buttons array. Add

    Array.Clear(buttons, 0, buttons.Length);
    

    I've also modified the removal loop to explicitly dispose of any resources held by the button as shown here on MSDN.

    for (int i = 0; i < buttons.Length; i++)
    {
        //you can change break to 'continue' if you remove buttons
        //from the array randomly so that if it encounters a null 
        //it will carry on reading the rest of the array.
        if (buttons[i] == null)
            break;  
    
    
        //dispose any button resources and event handlers so no references remain
        buttons[i].Click -= new EventHandler(this.clickMe);
        this.Controls.Remove(buttons[i]);
        buttons[i].Dispose(); 
    }
    
    Array.Clear(buttons, 0, buttons.Length);
    
    //..