[c#] How to hide TabPage from TabControl

How to hide TabPage from TabControl in WinForms 2.0?

This question is related to c# winforms tabcontrol tabpage

The answer is


+1 for microsoft :-) .
I managed to do it this way:
(it assumes you have a Next button that displays the next TabPage - tabSteps is the name of the Tab control)
At start up, save all the tabpages in a proper list.
When user presses Next button, remove all the TabPages in the tab control, then add that with the proper index:

int step = -1;
List<TabPage> savedTabPages;

private void FMain_Load(object sender, EventArgs e) {
    // save all tabpages in the list
    savedTabPages = new List<TabPage>();
    foreach (TabPage tp in tabSteps.TabPages) {
        savedTabPages.Add(tp);
    }
    SelectNextStep();
}

private void SelectNextStep() {
    step++;
    // remove all tabs
    for (int i = tabSteps.TabPages.Count - 1; i >= 0 ; i--) {
            tabSteps.TabPages.Remove(tabSteps.TabPages[i]);
    }

    // add required tab
    tabSteps.TabPages.Add(savedTabPages[step]);
}

private void btnNext_Click(object sender, EventArgs e) {
    SelectNextStep();
}

Update

public class TabControlHelper {
    private TabControl tc;
    private List<TabPage> pages;
    public TabControlHelper(TabControl tabControl) {
        tc = tabControl;
        pages = new List<TabPage>();
        foreach (TabPage p in tc.TabPages) {
            pages.Add(p);
        }
    }

    public void HideAllPages() {
        foreach(TabPage p in pages) {
            tc.TabPages.Remove(p);
        }
    }

    public void ShowAllPages() {
        foreach (TabPage p in pages) {
            tc.TabPages.Add(p);
        }
    }

    public void HidePage(TabPage tp) {
        tc.TabPages.Remove(tp);
    }        

    public void ShowPage(TabPage tp) {
        tc.TabPages.Add(tp);
    }
}  

As a cheap work around, I've used a label to cover up the tabs I wanted to hide.

We can then use the visible prop of the label as a substitute. If anyone does go this route, don't forget to handle keyboard strokes or visibility events. You wouldn't want the left right cursor keys exposing the tab you're trying to hide.


you can set the parent of the tabpage to null for hiding and to show just set tabpage parent to the tabcontrol


I realize the question is old, and the accepted answer is old, but ...

At least in .NET 4.0 ...

To hide a tab:

tabControl.TabPages.Remove(tabPage);

To put it back:

tabControl.TabPages.Insert(index, tabPage);

TabPages works so much better than Controls for this.


Code Snippet for Hiding a TabPage

private void HideTab1_Click(object sender, EventArgs e)
{
    tabControl1.TabPages.Remove(tabPage1);
}

Code Snippet for Showing a TabPage

private void ShowTab1_Click(object sender, EventArgs e)
{
    tabControl1.TabPages.Add(tabPage1);
}

I combined the answer from @Jack Griffin and the one from @amazedsaint (the dotnetspider code snippet respectively) into a single TabControlHelper.

The TabControlHelper lets you:

  • Show / Hide all tab pages
  • Show / Hide single tab pages
  • Keep the original position of the tab pages
  • Swap tab pages

public class TabControlHelper
{
    private TabControl _tabControl;
    private List<KeyValuePair<TabPage, int>> _pagesIndexed;
    public TabControlHelper(TabControl tabControl)
    {
        _tabControl = tabControl;
        _pagesIndexed = new List<KeyValuePair<TabPage, int>>();

        for (int i = 0; i < tabControl.TabPages.Count; i++)
        {
            _pagesIndexed.Add(new KeyValuePair<TabPage, int> (tabControl.TabPages[i], i ));
        }
    }

    public void HideAllPages()
    {
        for (int i = 0; i < _pagesIndexed.Count; i++)
        {
            _tabControl.TabPages.Remove(_pagesIndexed[i].Key);
        }
    }

    public void ShowAllPages()
    {
        for (int i = 0; i < _pagesIndexed.Count; i++)
        {
            _tabControl.TabPages.Add(_pagesIndexed[i].Key);
        }
    }

    public void HidePage(TabPage tabpage)
    {
        if (!_tabControl.TabPages.Contains(tabpage)) return;
        _tabControl.TabPages.Remove(tabpage);
    }

    public void ShowPage(TabPage tabpage)
    {
        if (_tabControl.TabPages.Contains(tabpage)) return;
        InsertTabPage(GetTabPage(tabpage).Key, GetTabPage(tabpage).Value);
    }

    private void InsertTabPage(TabPage tabpage, int index)
    {
        if (index < 0 || index > _tabControl.TabCount)
            throw new ArgumentException("Index out of Range.");
        _tabControl.TabPages.Add(tabpage);
        if (index < _tabControl.TabCount - 1)
            do
            {
                SwapTabPages(tabpage, (_tabControl.TabPages[_tabControl.TabPages.IndexOf(tabpage) - 1]));
            }
            while (_tabControl.TabPages.IndexOf(tabpage) != index);
        _tabControl.SelectedTab = tabpage;
    }

    private void SwapTabPages(TabPage tabpage1, TabPage tabpage2)
    {
        if (_tabControl.TabPages.Contains(tabpage1) == false || _tabControl.TabPages.Contains(tabpage2) == false)
            throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");

        int Index1 = _tabControl.TabPages.IndexOf(tabpage1);
        int Index2 = _tabControl.TabPages.IndexOf(tabpage2);
        _tabControl.TabPages[Index1] = tabpage2;
        _tabControl.TabPages[Index2] = tabpage1;
    }

    private KeyValuePair<TabPage, int> GetTabPage(TabPage tabpage)
    {
        return _pagesIndexed.Where(p => p.Key == tabpage).First();
    }
}

Well, if you don't want to mess up existing code and just want to hide a tab, you could modify the compiler generated code to comment the line which adds the tab to the tabcontrol.

For example: The following line adds a tab named "readformatcardpage" to a Tabcontrol named "tabcontrol"

this.tabcontrol.Controls.Add(this.readformatcardpage);

The following will prevent addition of the tab to the tabcontrol

//this.tabcontrol.Controls.Add(this.readformatcardpage);


// inVisible
TabPage page2 = tabControl1.TabPages[0];
page2.Visible= false;
//Visible 
page2.Visible= true;
// disable
TabPage page2 = tabControl1.TabPages[0];
page2.Enabled = false;
// enable
page2.Enabled = true;
//Hide
tabCtrlTagInfo.TabPages(0).Hide()
tabCtrlTagInfo.TabPages(0).Show()

Just copy paste and try it,the above code has been tested in vs2010, it works.


Solutions provided so far are way too complicated. Read the easiest solution at: http://www.codeproject.com/Questions/614157/How-to-Hide-TabControl-Headers

You could use this method to make them invisible at run time:

private void HideAllTabsOnTabControl(TabControl theTabControl)
{
  theTabControl.Appearance = TabAppearance.FlatButtons;
  theTabControl.ItemSize = new Size(0, 1);
  theTabControl.SizeMode = TabSizeMode.Fixed;
}

Hide TabPage and Remove the Header:

this.tabPage1.Hide();
this.tabPage3.Hide();
this.tabPage5.Hide();
tabControl1.TabPages.Remove(tabPage1);
tabControl1.TabPages.Remove(tabPage3);
tabControl1.TabPages.Remove(tabPage5);

Show TabPage and Visible the Header:

tabControl1.TabPages.Insert(0,tabPage1);
tabControl1.TabPages.Insert(2, tabPage3);
tabControl1.TabPages.Insert(4, tabPage5);
this.tabPage1.Show();
this.tabPage3.Show();
this.tabPage5.Show();
tabControl1.SelectedTab = tabPage1;

private System.Windows.Forms.TabControl _tabControl;
private System.Windows.Forms.TabPage _tabPage1;
private System.Windows.Forms.TabPage _tabPage2;

...
// Initialise the controls
...

// "hides" tab page 2
_tabControl.TabPages.Remove(_tabPage2);

// "shows" tab page 2
// if the tab control does not contain tabpage2
if (! _tabControl.TabPages.Contains(_tabPage2))
{
    _tabControl.TabPages.Add(_tabPage2);
}

    public static Action<Func<TabPage, bool>> GetTabHider(this TabControl container) {
        if (container == null) throw new ArgumentNullException("container");

        var orderedCache = new List<TabPage>();
        var orderedEnumerator = container.TabPages.GetEnumerator();
        while (orderedEnumerator.MoveNext()) {
            var current = orderedEnumerator.Current as TabPage;
            if (current != null) {
                orderedCache.Add(current);
            }
        }

        return (Func<TabPage, bool> where) => {
            if (where == null) throw new ArgumentNullException("where");

            container.TabPages.Clear();
            foreach (TabPage page in orderedCache) {
                if (where(page)) {
                    container.TabPages.Add(page);
                }
            }
        };
    }

Use it like this:

    var hider = this.TabContainer1.GetTabHider();
    hider((tab) => tab.Text != "tabPage1");
    hider((tab) => tab.Text != "tabpage2");

The original ordering of the tabs is kept in a List that is completely hidden inside the anonymous function. Keep a reference to the function instance and you retain your original tab order.


Not sure about "Winforms 2.0" but this is tried and proven:

http://www.mostthingsweb.com/2011/01/hiding-tab-headers-on-a-tabcontrol-in-c/


Visiblity property has not been implemented on the Tabpages, and there is no Insert method also.

You need to manually insert and remove tab pages.

Here is a work around for the same.

http://www.dotnetspider.com/resources/18344-Hiding-Showing-Tabpages-Tabcontrol.aspx


Variant 1

In order to avoid visual klikering you might need to use:

bindingSource.RaiseListChangeEvent = false 

or

myTabControl.RaiseSelectedIndexChanged = false

Remove a tab page:

myTabControl.Remove(myTabPage);

Add a tab page:

myTabControl.Add(myTabPage);

Insert a tab page at specific location:

myTabControl.Insert(2, myTabPage);

Do not forget to revers the changes:

bindingSource.RaiseListChangeEvent = true;

or

myTabControl.RaiseSelectedIndexChanged = true;

Variant 2

myTabPage.parent = null;
myTabPage.parent = myTabControl;

TabPage pageListe, pageDetay;
bool isDetay = false;

private void btnListeDetay_Click(object sender, EventArgs e)
{
    if (isDetay)
    {
        isDetay = false;
        tc.TabPages.Remove(tpKayit);
        tc.TabPages.Insert(0,pageListe);
    }
    else
    {
        tc.TabPages.Remove(tpListe);
        tc.TabPages.Insert(0,pageDetay);
        isDetay = true;
    }
}

I also had this question. tabPage.Visible is not implemented as stated earlier, which was a great help (+1). I found you can override the control and this will work. A bit of necroposting, but I thought to post my solution here for others...

    [System.ComponentModel.DesignerCategory("Code")]
public class MyTabPage : TabPage
{
    private TabControl _parent;
    private bool _isVisible;
    private int _index;
    public new bool Visible
    {
        get { return _isVisible; }
        set
        {
            if (_parent == null) _parent = this.Parent as TabControl;
            if (_parent == null) return;

            if (_index < 0) _index = _parent.TabPages.IndexOf(this);
            if (value && !_parent.TabPages.Contains(this))
            {
                if (_index > 0) _parent.TabPages.Insert(_index, this);
                else _parent.TabPages.Add(this);
            }
            else if (!value && _parent.TabPages.Contains(this)) _parent.TabPages.Remove(this);

            _isVisible = value;
            base.Visible = value;
        }
    }

    protected override void InitLayout()
    {
        base.InitLayout();
        _parent = Parent as TabControl;
    }
}

In WPF, it's pretty easy:

Assuming you've given the TabItem a name, e.g.,

<TabItem Header="Admin" Name="adminTab" Visibility="Hidden">
<!-- tab content -->
</TabItem>

You could have the following in the code behind the form:

 if (user.AccessLevel == AccessLevelEnum.Admin)
 {
     adminTab.Visibility = System.Windows.Visibility.Visible;
 }

It should be noted that a User object named user has been created with it's AccessLevel property set to one of the user-defined enum values of AccessLevelEnum... whatever; it's just a condition by which I decide to show the tab or not.


Create a new empty class and past this inside it:

using System.Windows.Forms;

namespace ExtensionMethods
{
    public static class TabPageExtensions
    {

        public static bool IsVisible(this TabPage tabPage)
        {
            if (tabPage.Parent == null)
                return false;
            else if (tabPage.Parent.Contains(tabPage))
                return true;
            else
                return false;
        }

        public static void HidePage(this TabPage tabPage)
        {
            TabControl parent = (TabControl)tabPage.Parent;
            parent.TabPages.Remove(tabPage);
        }

        public static void ShowPageInTabControl(this TabPage tabPage,TabControl parent)
        {
            parent.TabPages.Add(tabPage);
        }
    }
}

2- Add reference to ExtensionMethods namespace in your form code:

using ExtensionMethods;

3- Now you can use yourTabPage.IsVisible(); to check its visibility, yourTabPage.HidePage(); to hide it, and yourTabPage.ShowPageInTabControl(parentTabControl); to show it.


If you are talking about AjaxTabControlExtender then set TabIndex of every tabs and set Visible property True/False according to your need.

myTab.Tabs[1].Visible=true/false;


I've used the same approach but the problem is that when tab page was removed from the tab control TabPages list, it is removed from the tab page Controls list also. And it is not disposed when form is disposed.

So if you have a lot of such "hidden" tab pages, you can get windows handle quota exceeded error and only application restart will fix it.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to tabcontrol

Check if a specific tab page is selected (active) Activate tabpage of TabControl Hiding and Showing TabPages in tabControl WPF TabItem Header Styling Is there Selected Tab Changed Event in the standard WPF Tab Control How to hide TabPage from TabControl How can I disable a tab inside a TabControl?

Examples related to tabpage

Can't Load URL: The domain of this URL isn't included in the app's domains Check if a specific tab page is selected (active) Activate tabpage of TabControl Hiding and Showing TabPages in tabControl How to hide TabPage from TabControl