0

I have a dynamically created TableLayoutPanel, in which each cell (except those in the first row) contains a control that is added during runtime (two of them with EventHandlers). I need be able to clear out the contents of that table, so I wrote a method for this purpose:

private void clearDataLogs()
{
    tableLayoutPanel_dataLogs.Visible = false;
    button_saveSelectedLogs.Visible = false;
    tableLayoutPanel_dataLogs.SuspendLayout();
    int loopCount = 0;
    TableLayoutControlCollection controls = tableLayoutPanel_dataLogs.Controls;
    foreach (Control control in controls)
    {
        var count = controls.Count;
        loopCount++;
        int row = tableLayoutPanel_dataLogs.GetCellPosition(control).Row;
        if (row != 0)
        {
            if (control.Name.Contains(ControlNames.checkBoxSelectedName)) ((CheckBox)control).CheckedChanged -= new System.EventHandler(this.checkBox_getAnyDataLog_CheckedChanged);
            else if (control.Name.Contains(ControlNames.textBoxFileNameName)) ((TextBox)control).TextChanged -= new System.EventHandler(this.textBoxFileName_TextChanged);
            tableLayoutPanel_dataLogs.Controls.Remove(control);
            control.Dispose();
        }
    }

    while (tableLayoutPanel_dataLogs.RowCount > 1)
    {
        int row = tableLayoutPanel_dataLogs.RowCount - 1;
        tableLayoutPanel_dataLogs.RowStyles.RemoveAt(row);
        tableLayoutPanel_dataLogs.RowCount--;
    }
    tableLayoutPanel_dataLogs.Size = new System.Drawing.Size(530, 56);
    tableLayoutPanel_dataLogs.AutoScroll = true;
    tableLayoutPanel_dataLogs.Visible = false;
    tableLayoutPanel_dataLogs.ResumeLayout();
    tableLayoutPanel_dataLogs.PerformLayout();
}

The code should iterate through every control in the panel, removing the controls in each row except the first row. I even added checks to get rid of the handlers for the controls that will have them.

The problem is this: when I run the code, it never seems to get all the controls. The count and loopCount variables in there are just for debugging. In the simplest case, count is 14, but loopCount gets to 9 or 10 at the end of the loop. This is the most vexing part: the controls that get skipped are not always the same each time I run the method!!!

What is going on with this, and how might I fix it?

Adam Hoffman
  • 109
  • 1
  • 14
  • 2
    you are iterating on the same thing you are removing from. use a for n loop and go backwards – Ňɏssa Pøngjǣrdenlarp Jan 22 '15 at 01:12
  • 1
    OK, changed the foreach to `for (int i = controls.Count - 1; i > 0; i--)` and added the oh-so-important line `Control control = controls[i];` which now allows me to remove and dispose. Works fine now. Thanks! – Adam Hoffman Jan 22 '15 at 01:23

0 Answers0