views:

547

answers:

1

How to implement some of the tabs need to close by some events or some button click?

+1  A: 

You can remove a tab from TabControl like this:

tabControl1.TabPages.Remove(tabControl1.SelectedTab);

When closing multiple tabs you may want to remove the tabs with a higher index number first as the index of tab pages change when you pop a tab:

private void button1_Click(object sender, EventArgs e)
{
    // Close second and fourth tab
    if (tabControl1.TabPages.Count > 3)
    {
        // Work backwards when removing tabs
        tabControl1.TabPages.RemoveAt(3);
        tabControl1.TabPages.RemoveAt(1);
    }
}

If you need the tabs again after closing them, then Hide() will not be helpful. You should store a reference for each tab in memory and add or insert them later:

tabControl1.TabPages.Remove(tabPage1);
tabControl1.TabPages.Add(tabPage1);
tabControl1.TabPages.Insert(0, tabPage1);

Using the example below you may keep a collection of tabs that you closed and push them to the TabControl later on. Preferably you will create a small class that allows you to save the position and reference to tabs in. This example uses a generics List and Control.Tag that does the same.

private List<TabPage> tabsClosed = new List<TabPage>();

private void button1_Click(object sender, EventArgs e)
{
    // Close second and fourth tab
    if (tabControl1.TabCount > 3)
    {
        // Keep a reference to tabs in memory before closing them
        tabsClosed.Add(tabControl1.TabPages[1]);
        tabsClosed.Add(tabControl1.TabPages[3]);

        // Store the tabs position somewhere
        tabControl1.TabPages[1].Tag = 1;
        tabControl1.TabPages[3].Tag = 3;

        // Work backwards when removing tabs
        tabControl1.TabPages.RemoveAt(3);
        tabControl1.TabPages.RemoveAt(1);
    }
}

private void button2_Click(object sender, EventArgs e)
{
    foreach (TabPage tab in tabsClosed)
    {
        //tabControl1.Controls.Add(tab);
        tabControl1.TabPages.Insert((int)tab.Tag, tab);
    }
    tabsClosed.Clear();
}
Patrick de Kleijn