C# – Loop through controls in TabControl

cforeachloopstabcontrolwinforms

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?

Best Answer

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
        }