views:

54

answers:

2

Hi,

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?

+1  A: 

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);
    }
Hans Passant
i am finding difficult to add the tab page... can u post some full eg. i understood your method but wonder how to refrence a tab while adding as it has been previously removed
KoolKabin
Just add a member to your class. The Windows Forms designer already does that, like "tabPage1".
Hans Passant
liek to refer tabpage1 do i need to write me.TabPages("tabPage1") or what?
KoolKabin
No, just use tabPage1. It is a member of the form class.
Hans Passant
hye it worked even wthout the hiddenpages variable... so any special use of it?
KoolKabin
Yes, important to get the hidden page disposed when the form closes.
Hans Passant
A: 

I have my sample code working but want to make it somewhat more better refrencing the tab from list:

Public Class Form1
    Dim State1 As Integer = 1
    Dim AllTabs As List(Of TabPage) = New List(Of TabPage)

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Check1(State1)
        State1 = CInt(IIf(State1 = 1, 0, 1))
    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AllTabs.Add(TabControl1.TabPages("TabPage1"))
        AllTabs.Add(TabControl1.TabPages("TabPage2"))
    End Sub

    Sub Check1(ByVal No As Integer)
        If TabControl1.TabPages.ContainsKey("TabPage1") Then
            TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage1"))
        End If
        If TabControl1.TabPages.ContainsKey("TabPage2") Then
            TabControl1.TabPages.Remove(TabControl1.TabPages("TabPage2"))
        End If
        TabControl1.TabPages.Add(AllTabs(No))
    End Sub
End Class
KoolKabin