Skip Navigation LinksHome > View Post
Show and Hide tab pages in Windows Forms

It seems a lot of people believe it is not possible to show and hide a TabPage in a TabControl on a windows form. This is not that surprising since the Show and Hide methods of the TabPage class do nothing whatsoever.

If you refer to the MSDN documentation about the TabPage class, it states the following:

"the Hide method of the TabPage will not hide the tab. To hide the tab, you must remove the TabPage control from the TabControl.TabPages collection."
Hence the correct way to hide and show a tab using code is shown below.

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 (_tabControl.TabPages.Contains(_tabPage2))
{
    _tabControl.TabPages.Add(_tabPage2);
}

Note: You should test whether the tab page is already in the TabPages collection before adding it, otherwise it will be displayed twice
The last TabPage added to the TabPages collection will be displayed last, so if you are hiding and showing multiple tabs you might also want to put in some code to make sure the tabs are in the right order. I simply remove all the tabs first, before adding them again as shown below.


// Suspend and resume layout to avoid flickering.
_tabControl.SuspendLayout();
_tabControl.TabPages.Clear();
_tabControl.TabPages.Add(_tabPage1);
_tabControl.TabPages.Add(_tabPage2);
_tabControl.ResumeLayout();

Note: If you use the approach above you don't need to test whether the TabPages collection already contains the tab page(s) you are adding.

Bruusi Post By Bruusi
12:10
24 Apr 2006

» Next Post: Why the fancy UI
« Previous Post: Time taken to render a page in ASP.NET

Comments:

Posted by Syed Arshad @ 09 Dec 2007 00:46
Very nice to hide and display of tab pages and i utilzing the above code in my project. Its working fine.

Thanks.

Posted by Searock @ 16 Feb 2009 21:49
Thanks a lot. your post helped me a lot in my project

Post a comment:

Name  

E-mail (never shared)

URL

Comments  

Captcha ImageRefresh Image
What's this?
Enter code above