Search code examples
c#tabpage

Deleting controls from a tabPage


I am trying to delete buttons made at runtime on a tabPage. I made a function that should go through all the controls on that tabPage, but for some reason only half of the buttons made are deleted each time it is called. (There are 8 buttons on the page, and I want all deleted)

foreach(var ctr in tabControl.SelectedTab.Controls)
{
    if (ctr is Button)
    {
        if (ctr is Button) { tabControl.SelectedTab.Controls.Remove((Button)ctr); }
    }
}

I even tried doing the following, only met with the same problem,

for (int i = 0; i < 8; i++)
    {
        tabControl.SelectedTab.Controls.Remove(
         ((Button)tabControl.SelectedTab.Controls[i]));
    }

However, when I try debugging, it only recognizes the 1st, 3rd, 5th, and 7th buttons made on the tabPage, and deletes only them, leaving 4. If I try doing it a second time, again, it deletes half, leaving 2. I initialize each button as follows.

for (int i = 0; i < 8; i++)
    {
        tempButton[i] = new Button();
        tabControl.SelectedTab.Controls.Add(tempButton[i]);
        tempButton[i].AutoSize = true;
        tempButton[i].Location = new System.Drawing.Point(
                   100 + (150 * (i % 4)), 175 + (175 * (int)(.25 * i)));
        //tempButton[i].Name = "tempButton" + i.ToString();
        tempButton[i].Text = names[i];
        tempButton[i].Size = new System.Drawing.Size(35, 13);
        tempButton[i].TabIndex = i;
    }

Solution

  • By the time you remove Controls[i], the next time Controls[i] has changed, as the 2nd button might be the 1st after removal of a button.

    You might try to get all the buttons and save it to a temp collection, instead of directly referencing them with SelectedTab.Controls[i]:

    var buttons = tabControl.SelectedTab.Controls.OfType<Button>()
    for (int i = 0; i < buttons.Count; i++) {
       tabControl.SelectedTab.Controls.Remove(buttons[i]);
    }
    

    BTW: You might consider hide these buttons by changing the Visible property.