How to copy control values from one tab to another

I'm able to insert a form at runtime on a new tab.  It has split containers with labels, textboxs and a tablelayoutpanel with many controls. The user enters information on the first tab.  Now I want to make a copy.  My copy has everything the first tab has except the user information.  I have this code but do not know how to reference specific controls on one tab and assign it to the same exact positioned as well as named control on the other tab.  This loop needs to be more generic to pickup all types of control values.  I do not know what to write to actually reference tabpage1 & tabpage2 in the loop.

My TabControl is named: BOM_TabControl1
The form copied to a tab is:  PDF_ML_Form
Thank You

            Dim myTabPage As New TabPage()
            Dim tmpYourName As String
            BOM_TabControl1.SelectTab(BOM_TabControl1.Controls.Count - 1)
            myTabPage.Text = "Copy of " & myTabPage.Text

            MyForm = New PDF_ML_Form

            MyForm.FormBorderStyle = Windows.Forms.FormBorderStyle.None
            MyForm.Dock = DockStyle.None
            MyForm.TopLevel = False
            MyForm.Anchor = AnchorStyles.Left
            MyForm.Anchor = AnchorStyles.Top
            MyForm.Anchor = AnchorStyles.Left
            ''MyForm.AutoScrollPosition = New Point(1, 1)

            ' Set location & size of main tab container
            MyForm.Size = New Size(MyForm.Width, PDF_ML_Form.Height)
            MyForm.AutoScrollPosition = New Point(1, 1)
            MyForm.AutoScroll = False

            ' Add cell values
            Dim x As Int16
            For x As Integer = 0 To tabpage1.Controls.Count - 1
                      if gettype(tabpage1.controls(i)) is GetType(TextBox) then
                    CType(tabpage2.controls(x), TextBox).text = CType(MyForm.Controls(x), TextBox).Text
                End If
            Next x

Who is Participating?
Craig YellickDatabase ArchitectCommented:
You have to store the data somewhere between the time the user enters it and later when you want to save it all. A datatable is the best way to do this, independent of the ultimate destination, and independent of where the data is referenced on the form.

If you bind textboxes to the datatable, then you don't need to copy values between controls. Instead you'd insert a new customer record, and copy values between records as desired. The textboxes will immediately display whichever record is selected at the moment. Datatables are designed to do this. It is a technique well worth learning as it will be used over and over in many contexts.

If you don't use a datatable and data binding then you will end up doing the same kind of looping activities to save data back out when the user wants to save everything.

If you want to copy values between controls, this implies that you have multiple instances of the controls.  The tab upon which the control is located isn't important. If you know the names of the two textboxes you can simply assign the .Text properties like so:

   TextBox7.Text = TextBox3.Text

The problem is that you don't know the names of the controls at design time. The controls like TextBox7 and TextBox3 are dynamically generated based on the user adding more customer tabs. So you will have to use looping techniques as you illustrated in your original question.  Below, a more streamlined and reliable approach.


1) Each tab page has an instance of the "PDF_ML_Form" form as the first control. This is where the sourceForm variable gets assigned.

2) The variable named newDataForm is the new instance of "PDF_ML_Form" that you have added or will add to the tab control.

The FOR..EACH loop looks only at TextBox controls and maps based on the name of the control.
    Dim sourceForm As Form = CType(TabControl1.TabPages(0).Controls(0), Form)
    For Each ctrl As Control In newDataForm.Controls
      If TypeOf ctrl Is TextBox Then
        ctrl.Text = CType(sourceForm.Controls(ctrl.Name), TextBox).Text
      End If

Open in new window

Craig YellickDatabase ArchitectCommented:
Do you need to have physically distinct controls on the other tab page?  You can set the control's Parent property from one tab page to another and back again very easily. If you place controls inside a container of some sort then all you need to do is assign the container's parent and all the child controls come along for the ride.

Below is some code I'm using right now in an application where multiple tabs share common controls. In my case it's a group box and grid, but it would work for any set of controls.
Private Sub tabMain_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles tabMain.SelectedIndexChanged
    ' File location options and results grid are the same for both tabs
    groupFileLocations.Parent = tabMain.SelectedTab
    gridResults.Parent = tabMain.SelectedTab
End Sub

Open in new window

GarySBAuthor Commented:
I may already have what you  are describing.  If you notice from my code I am copying all of my split containers  that are contained in a seperate form.  When the "MyForm = New PDF_ML_Form" is called, the load procedure of the form is executed and at that point I inject all of the values.  This occurs when the original tab is first created.  Now that I have this tab the user enters additional information.  Its this new information that is not carrying over.  The old is copied to the duplicate new tab because the load procedure still has the old values.  The names of the controls are therefore identical and not physically distinct on the other tab page.  Can we please use one variable from my code for me to understand.
How would it work to copy
NewTab_PDF_BOM_Part_Number(MLR).text from tab3 to tab7?

So, given what you described if I need to copy tab3 to tab7 would this call be correct?

My copy procedure:
               (my tabcontrol name)
              ' tab is now set to source. Store values, then change to tab7 and assign
              Source1string = NewTab_PDF_BOM_Part_Number(MLR).text
              Source2string = NewTab_PDF_BOM_Description(MLR).text

              ' tab is now set to destination. Assign values
              NewTab_PDF_BOM_Part_Number(MLR).text = Source1string
              NewTab_PDF_BOM_Description(MLR).text = Source2string

End copy procedure:

Private Sub BOM_TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles BOM_TabControl1.SelectedIndexChanged
    ' File location options and results grid are the same for both tabs
        ' the Panel1 has two split containers with every control I am trying to copy.
       IT DOES NOT LIKE THE SYNTAX BELOW and i tried with parenthesis.
       PDF_ML_Form.Panel1.Parent = BOM_TabControl1.SelectedTab = tmpTabLocation
End Sub
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Craig YellickDatabase ArchitectCommented:
I am not entirely certain of what is going on, but for sure the following line is a problem:

  PDF_ML_Form.Panel1.Parent = BOM_TabControl1.SelectedTab = tmpTabLocation

This line is assigning the .Parent property to the boolean result of comparing the .SelectedTab property to the tmpTabLocation variable. You only need this part:

  PDF_ML_Form.Panel1.Parent = BOM_TabControl1.SelectedTab

Which sets the parent to the newly selected tab.
GarySBAuthor Commented:
What about this line that is taking the empty form as the source.
MyForm = New PDF_ML_Form

How can PDF_ML_Form be set to the form residing on tab3.  
Would not that copy the form with all the information?  
Do you know how to reference the form on tab3 for this MyForm = New instruction?
Thank you for your help
GarySBAuthor Commented:
I do not think my last attempt will work.  The source has to come from the seperate new form.  So back to my original question.  Can you give me an example of just copying one variable textbox1.text from tab3 to tab7?
Craig YellickDatabase ArchitectCommented:
Your original question and follow-up references talk about creating a new form at runtime and making it part of a new tab.  At least that's what I understand by "I'm able to insert a form at runtime on a new tab."

My recommendation is to NOT make copies of anything, and instead simply move existing controls between tabs by setting the container control's .Parent property. This approach is much easier to implement, test and debug. However, if you have needs that require a copy this won't work.

Let's establish a too-simple-to-fail base line and make sure we're both talking about the same thing.

1. Create a new VB WinForms project.
2. On Form1, add a Tab control (which has two tabs by default).
3. On TabPage1, add a textbox and a checkbox.
4. In the TabControl1_SelectedIndexChanged event, add the following line:
       TextBox1.Parent = TabControl1.SelectedTab
5. Run the application and note that the checkbox does not move between tabs but the textbox does.

The above is the essence of the technique that I am describing.  If you need to be able to dynamically add a tab at runtime you can do so by either hiding/unhiding a tab that already exists or by creating a new tab, like so:

   TabControl1.TabPages.Add(New TabPage)

Either way the TabControl1_SelectedIndexChanged event will accomplish the same thing.

Your situation is more complex but I want to start with something very simple upon which we can build.
GarySBAuthor Commented:
I feel that I already have a good method of copying my form because before it was very hard to copy from a tab and get the controls in the same exact location and layout.  Now that it is in a form each tab looks the same.

Yes, I am able to make an exact copy (empty shell) of the form at runtime.  Its the transferring values.  May be this will be clearer.  On tab1 I have a textbox in my form that has its text = "Sears". I make a copy of it NOT from tab1, but from my form to a new tab7.  Now my new tab7 has the textbox in the same exact place, but nothing in it.  If I use the Parent method it will move the control and not allow independent values on each tab.

Right, the checkbox does move between tabs and I may have 20 tabs.  Each time the user clicks a different tab the value for each control will be different.  Each tab represents another customer.  The name field will be different on each tab.  So when they click my copy button I just need to transfer the values from the present tab to the new one.  
Please try one more time, Thanks
Craig YellickDatabase ArchitectCommented:
Are customer records stored in a datatable? Are the textboxes and other controls bound to that data source? Is the user allowed to move between tabs and make random changes on multiple tabs without saving?

My gut reaction is that you do not need to copy controls. You can tie the user's tab clicks into navigation between records. TextBox and other data-bound controls will automatically handle the display of different customer information.
GarySBAuthor Commented:
Is the user allowed to move between tabs and make random changes on multiple tabs without saving?  YES

The total project (tabs) is saved at the end to a external file similar .doc or .xls which I have not created yet.  When the program opens this file will have to be read to recreate the tabs because although the data can be in the users database, if they send this .doc file to someone else, they wont have the records.

I do see your point. If the information is saved to a database it can be read easily from anywhere in the program.   Since I do need to save all the tabs as a project it just might make sense to invest in doing that.  However, it restricts me forcing me to save and read from the database even for a single variable change each time.  Otherwise they will get the old value from the database.  If I can just reference a variable textbox.text on a specific tab I would be able to work the rest out.
Craig YellickDatabase ArchitectCommented:
The use of a datatable for customer information is completely decoupled from database access. You could implement the entire application using an XML document containing all of the customer information. Or you could store it in any other database that might be handy (Access/Jet, SQL Server Express, etc).

100% of the edits to textboxes and other controls is accomplished in memory associated with the customer datatable. The datatable keeps track of record status so it knows which are edits versus inserts vs deletes. So no physical database access is involved unless and until you call some kind of Save method that moves the edits out of memory and out to the database (or XML document as the case may be).

Basing your design on databound textboxes and a datatable will offer a vast array of built-in .NET features, including reporting, filtering, searching and so on.
GarySBAuthor Commented:
I'm using SQL 2005 at the moment and do not wish to use another database system.  I do plan on making my own type of XML file to store the Tabs information as I mentioned before.  My goal is still to be able to reference a controls text value from whatever tab I require.  You've given me some good points, but at the end of the day I still need to be able to copy the text from one variable to another.  Its just a question of combining the right object names together.

This is what i am trying to accomplish
TabControlName.TabNumber.Textbox7.text = TabControlName.TabNumber.Textbox3.text
GarySBAuthor Commented:
Your last response was the most helpful, Thank You
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.