Tab selection

How do I implement some of the tabs that need to be closed by some events or a button clicked?

0


source to share


1 answer


You can remove the tab from the TabControl like this:

tabControl1.TabPages.Remove(tabControl1.SelectedTab);

      

When closing multiple tabs, you can first delete the tabs with a higher index number when the tab index changes when the tab is clicked:

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()

it won't be helpful. You have to keep the link for each tab in memory and add or paste it later:

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

      

Using the example below, you can save a collection of tabs that you closed and insert them into a TabControl later. Preferably you create a small class that allows you to store the position and link to the tabs. This example uses a common List and Control.Tag, which 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();
}

      

+1


source







All Articles