Duplicating Tab Pages

The Tab Control can simplify your forms layout, but it’s not obvious how to set it up for an unknown number of identical pages.  This example shows how

The secret to this trick is to create your own class that defines the tab page you want to duplicate.  Then you create as many instances of that tab page as you need to use, and add them into the tab control.

To use this example, create a form that contains:

  • a textbox named tbxPageCount (the page count, and the selected page number)
  • a button named btnRefresh (to create the duplicate pages)
  • a button named btnUpdate (to put data into the selected tab page)
  • a textbox named tbxData1 (the first test data)
  • a textbox named tbxData2 (the second test data)
  • a tab control name TabControl1

Add this class after the Form1 class in the code for the new form.   This defines the page for the tab control.  Note that it takes a page number as an argument to the constructor.

Class myTabPage
  Inherits TabPage
  Public TextboxData1 As TextBox = New TextBox
  Public TextBoxData2 As TextBox = New TextBox
  Public Sub New(ByVal PageNo As Integer)
    MyBase.Text = "Page: " & PageNo.ToString
    TextboxData1.Location = New Point(60, 40)
    TextBoxData2.Location = New Point(260, 40)
  End Sub
End Class

The class defines a simple tab page that has two textboxes.

Now add the following code as the Form1 class.  This is code for the two button click events.  The Refresh button clears any current tab pages, then adds identical tab pages according to the number entered in the Page Count text box.  The Update buton shows how to reference the controls on a tab page.  It copies the text from the two Data text boxes into the tab page indicated by the Page Count text box value.  (Note that this example has no checking, and can be easily crashed).

Public Class Form1
Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnRefresh.Click
For I As Integer = 1 To CInt(tbxPageCount.Text)
TabControl1.TabPages.Add(New myTabPage(I))
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnUpdate.Click
Dim TP As myTabPage = CType(TabControl1.TabPages(CInt(tbxPageCount.Text) - 1), myTabPage)
TP.Data1.Text = tbxData1.Text
TP.Data2.Text = tbxData2.Text
End Sub
End Class

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s