Loop through controls in TabControl

时光毁灭记忆、已成空白 提交于 2019-12-05 14:37:56
Joseph

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
        }

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.

Example where I wanted to get the DataGridView in a particular tab for an application I wrote.

TabPage pg = tabControl1.SelectedTab;

// Get all the controls here
Control.ControlCollection col = pg.Controls;

// should have only one dgv
foreach (Control myControl in col)
{
    if (myControl.ToString() == "System.Windows.Forms.DataGridView")
    {
        DataGridView tempdgv = (DataGridView)myControl;   
        tempdgv.SelectAll();
    }
}
Ragepotato

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...
}

TabControl has a SelectedTab property, so you'd do something like this:

foreach(Control c in tabControl.SelectedTab.Controls)
{
    //do checks
}
foreach (Control c in this.tabControl1.SelectedTab.Controls)
{
  // Do something
}

I had the need to disable or enable controls of a tab as well. I had to go a bit more generic though. Hope it helps people and I didn't make a mistake

    private void toggleControls(Control control, bool state)
    {
        foreach (Control c in control.Controls)
        {
            c.Enabled = state;
            if (c is Control)
            {
                toggleControls(c, state);
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!