devxlogo

Hiding pages of a TabControl

Hiding pages of a TabControl

Sometimes you may need to hide or show some pages of a TabControl according to the information you want to show, basing on the currently logged-in user for example (users with low privileges won’t be able to get all the information or to change records). To do this, you may attempt to add or remove the pages to and from the TabControl’s TabPages collection. This approach seems to work fine at first, until unfortunately you realize that after you’ve removed a page from the collection, you can no longer close the form. It doesn’t matter what you do – press CTRL+F4, click the Close item of the form’s system menu or the X icon on the title bar – the form won’t close.

Apparently there is a bug that prevents to close the form if any of the child TabPage instances doesn’t have a parent TabControl. However, what’s interesting is that if you remove a page from a TabControl and add it to another TabControl, then the form closes correctly.

So, when you need to hide a page from your TabControl, just add it to another invisible TabControl (set its Visible property to False). You don’t even need to explicitly remove the page from the first control, this will be automatically done when the page is added to the second control’s TabPages collection. The following line shows how to do this:

TabControl2.TabPages.Add(pageToHide)

Next, when you want to re-show the page, you have to re-add it to the original control. Be careful doing this though, because if you just add the page as we did in the previous line of code the page will be added after the existent pages, not in its original position. The TabPages collection doesn’t expose an Insert method that allows you to insert the page in the desired position, as other collections do. A simple work around to this last issue is to remove all the pages from the first TabControl, and then add them all back in the right order. Here it is an example:

' remove all the pagesTabControl1.TabPages.Clear()' add all the pages in the right orderTabControl1.TabPages.AddRange(New TabPage() {pageToHide, page2, page3})

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist