Loop through controls in TabControl

24,323

Solution 1

As for looping through a TabControl's controls, you need to use the Controls property.

Here's an MSDN article on the TabControl.

Example:

        TabPage page = aTabControl.SelectedTab;

        var controls = page.Controls;

        foreach (var control in controls)
        {
            //do stuff
        }

Solution 2

I feel it's important to note that, in general, you should take a more structured approach to your application. E.g., instead of having all the controls on three tab pages, include exactly one UserControl on each tabpage. A CarUserControl, PetUserControl, and AdminUserControl e.g. Then each user control knows how to create the proper respective data structure so you don't have to manually munge it all together at the same level of abstraction using inter-tab loops and whatnot.

Such a separation of concerns will make it much easier to reason about your program and is good practice for writing maintainable code for your future career.

Solution 3

The Controls property is the way to go...

foreach(Control c in currentTab.Controls)
{
    if(c is TextBox)
        // check for text change
    if(c is CheckBox)
        //check for check change
    etc...
}
Share:
24,323
Sesame
Author by

Sesame

Updated on March 29, 2020

Comments

  • Sesame
    Sesame about 4 years

    I am looking for a way to loop through controls on a particular tab of a tabcontrol. For example, I have a tabcontrol with the following tabs:

    Cars, Pets, Admin

    On each of these tabs are several controls to display/edit/save data, etc. On the "Save" button, I would like to loop through the controls for that particular tab to check whether all required fields have been filled in.

    So, if I am on the Cars tab and click "Save," I want to loop ONLY through the controls on the Cars tab and NOT the Pets or Admin tabs.

    How can achieve this result?