A TabControl
is just a fancy way to organize controls on the same form. The point is that they are on the same form! You probably know that you use Me
to access the current form, then .ControlName
to access the control. Consider a TabControl
with two tabs and on each tab there is a TextBox
. These TextBox
es are on the same form, so you still need to use
Me.TextBox1.Text = "Text 1" ' the same as TextBox1.Text = "Text 1", but I like to be explicit
Me.TextBox2.Text = "Text 2"
This you already knew, as your problem stemmed from this behavior. However, there are some tricks to help you. Consider a TabControl
with two tabs, and on page 1 there is a control named tc1TextBox1
and on page 2 tc2TextBox1
. I'm using the prefix to distinguish between the pages. An additional TextBox
on page 1 would be named tc1TextBox2
etc., then say you wanted CheckBox
es, you could have tc1CheckBox1
and tc1CheckBox2
etc. The way I would access them is with LINQ
Define an extension method in a module
Imports System.Runtime.CompilerServices
Public Module ExtensionMethods
<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
Dim result As New List(Of Control)
For Each ctrl As Control In parent.Controls
If TypeOf ctrl Is T Then result.Add(ctrl)
result.AddRange(ctrl.ChildControls(Of T)())
Next
Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function
End Module
This method returns you all the Control
s inside parent
, and all Control
s inside those, and so on, recursively. It also gives you an IEnumerable
List(Of Control)
in contrast to Control.Controls()
which is not IEnumerable
and only returns controls in the control, not in its containers.
Using LINQ, you can filter the results of ChildControls
by Type
or Name
. For instance, the code
Dim textBoxes = Me.ChildControls(Of TextBox)()
returns all the TextBox
es in Me. Let's take it a step further:
Dim textBoxes = Me.ChildControls(Of TextBox)().Where(Function(tb) tb.Name.StartsWith("tc1"))
returns all the TextBox
es with the prefix "tc1". So you see you can set up the controls on your form to better group them at runtime. Here's an idea specific for Excel sheets
Dim xlBook As Excel.Workbook
For i As Integer = 1 To 20
Dim nameString = "txtSheetName" & i.ToString() ' TextBoxes named txtSheetName1, txtSheetName2, etc.
xlBook.Sheets(i).Name = Me.ChildControls(Of TextBox)().Where(Function(tb) tb.Name = nameString).First().Text
Dim enabledString = "chkEnabled" & i.ToString() ' CheckBoxes named chkEnabled1, chkEnabled2, etc.
xlBook.Sheets(i).Enabled = Me.ChildControls(Of CheckBox)().Where(Function(tb) tb.Name = enabledString).First().Checked
'etc.
Next
which will loop over your tab control indices, and set properties for each corresponding excel sheet. This code should give you a good idea of a direction you can take.