I have a form with a bunch of tabs on it, but I don't want them to all be开发者_StackOverflow visible all the time. I've tried
For Each t In TabControl1.TabPages
t.Hide()
Next
TabControl1.TabPages("DateRange").Show()
in order to hide them all on doc load and then .Show() for just the tabs that I want at that time, but that apparently doesn't work that way, as all the tabs are still visible.
Then I tried
Private tabs As TabControl.TabPageCollection
For Each t In TabControl1.TabPages
tabs.Add(t) ' Object reference not set to an instance of an object. '
TabControl1.TabPages.Remove(t)
Next
TabControl1.TabPages.Add(tabs("DateRange"))
but I get a tabs is not set to an instance of an object... And I get errors if I try to use
tabs = New TabControl.TabPageCollection
its frustrating that .Hide or .Visible don't do what they are supposed to.
You're on the right path, except instead of
Private tabs As TabControl.TabPageCollection
use
Private tabs As New List(Of TabPage)
You cannot continue around the loop removing as the index moves when an item is removed.
Setup your tabs and then remove them one by one either by index or name:
tabctrl.TabPages.RemoveAt(indx)
For x = 0 To tabctrl.TabPages.Count - 1
If tabctrl.TabPages(x).Name.Equals(tabToRemove.Name) Then
tabctrl.TabPages.RemoveAt(x)
Exit For
End If
Next
Moving a page that needs to be hidden into a List is the simple approach. However, such a hidden page also needs to be disposed when the form closes. It won't be automatic anymore since the TabControl cannot see the page. And you can't ignore it, forgetting to dispose a control is a permanent leak. Make it look like this:
Public Class Form1
Private hiddenPages As New List(Of TabPage)
Friend Sub SetTabState(ByVal page As TabPage, ByVal visible As Boolean)
If visible Then
If TabControl1.TabPages.Contains(page) Then Exit Sub
hiddenPages.Remove(page)
TabControl1.TabPages.Add(page)
Else
If Not TabControl1.TabPages.Contains(page) Then Exit Sub
hiddenPages.Add(page)
TabControl1.TabPages.Remove(page)
End If
End Sub
Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
For Each page As TabPage In hiddenPages
page.Dispose()
Next
End Sub
End Class
精彩评论