Search code examples
vb.nettabcontroltabpage

Hiding and Showing TabPages in tabControl


I am trying to show or hide tabpages as per user choice. If user selects gender male then form for male in a tabpage "male" should be displayed and if user selects female then similar next form should be displayed in next tab "female"

I tried using

tabControl1.TabPages.Remove(...)

and

tabControl1.TabPages.Add(...)

It adds and removes the tabpages but doing so will loose my controls on tabpages too... i can't see them back. what's the problem here?


Solution

  • You could remove the tab page from the TabControl.TabPages collection and store it in a list. For example:

        private List<TabPage> hiddenPages = new List<TabPage>();
    
        private void EnablePage(TabPage page, bool enable) {
            if (enable) {
                tabControl1.TabPages.Add(page);
                hiddenPages.Remove(page);
            }
            else {
                tabControl1.TabPages.Remove(page);
                hiddenPages.Add(page);
            }
        }
    
        protected override void OnFormClosed(FormClosedEventArgs e) {
            foreach (var page in hiddenPages) page.Dispose();
            base.OnFormClosed(e);
        }