How to implement "close all tabs" for a tabcontrol

How do I implement the "close all other tabs" functionality for a tab control using the context menu bar?

+1


source to share


4 answers


I made a small application with one tabcontrol in the main window and a context menu connected to this tabcontrol.

Below is the handler for the context menu item:



        private void closeAllOtherToolStripMenuItem_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < this.tabControl1.TabCount; i++)
            if (i != tabControl1.SelectedIndex)
                tabControl1.TabPages.RemoveAt(i--);
    }

      

+3


source


Try this simple close all tabs code.



tabControl.TabPages.Clear()

      

+1


source


Before "closing all" your tabs, you must remove (and remove event handlers) any controls / objects that you create on each tab page. Alternatively, you can use the .Clear method on the TabPages collection instead of removing each tab in a loop.

0


source


The following code closes all tabs and ensures that the contents of the tabs are saved before closing it.

    private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
    {
        TabControl.TabPageCollection pages = tabControl1.TabPages;
        foreach (TabPage page in pages)
        {
            saveToolStripMenuItem_Click(sender, e);
            closeTabToolStripMenuItem_Click(sender, e);
        }

    }

      

0


source







All Articles