VB.NET•Write Once, Insert Anywhere

Listing 2. The TabControl's TabPages collection doesn't include an AddAt or InsertAt method, so you must code it yourself. Use the built-in Add method instead if you want to only add new tab pages to the end of the collection.

Public Class ShowHideTabControl
   Inherits System.Windows.Forms.TabControl

   Public Sub InsertTabAt( _
      ByVal whatTab As Windows.Forms.TabPage, _
      ByVal position As Integer)
      ' ----- Insert the indicated tab page at
      '       the 0-based place in the control.
      Dim usePosition As Integer
      Dim counter As Integer
      Dim holdTab As Windows.Forms.TabPage

      ' ----- Make sure this all fits.
      If (position > MyBase.TabPages.Count) Then
         usePosition = MyBase.TabPages.Count
      ElseIf (position < 0) Then
         usePosition = 0
      Else
         usePosition = position
      End If

      ' ----- Add in the tab page.
      MyBase.TabPages.Add(whatTab)

      ' ----- Now, we have to adjust all of the
      '       other tabs "after" this one.
      If (usePosition < _
            (MyBase.TabPages.Count - 1)) Then
         ' ----- Remove and add the "after" tabs.
         For counter = usePosition To _
               MyBase.TabPages.Count - 2
            holdTab = _
               MyBase.TabPages(usePosition)
            MyBase.TabPages.Remove(holdTab)
            MyBase.TabPages.Add(holdTab)
         Next counter
      End If
   End Sub
End Class