简体   繁体   中英

Controls.Find in TabPage inside TabPage

I have one TabControl2 inside TabControl1. TabControl2 is in all TabPages of TabControl1. In TabPage of TabControl2 is DataGridView and I need to work (Add.Rows etc) with this DataGridView. All is added programatically.

I am looking for the best way to find the right DataGridView so I would need something like :

DataGridView xxx = TabControl2.SelectedTab.Controls.Find("data_grid_view_name", false).FirstOrDefault() as DataGridView ***in TabControl1.SelectedTab***
Find this DataGridView by more :

Foreach (var y in TabControl1.Controls.OfType<Tabpage>())
{
//looks like a dirty code for me
}

This Linq query returns the first DataGridView in your nested TabControls :

var gridViews = from tp in this.tabControl1.TabPages.Cast<TabPage>()
                from tc in tp.Controls.OfType<TabControl>()
                from tp2 in tc.TabPages.Cast<TabPage>()
                from grid in tp2.Controls.OfType<DataGridView>()
                select grid;
DataGridView firstGrid = gridViews.FirstOrDefault();
// if(firstGrid != null) ...

我认为最直接的方法是:

tabControl1.Controls.Find("data_grid_view_name", true);

Another example:

string dgvName = "data_grid_view_name";
if (tabControl1.SelectedTab != null)
{
    var nestedTabControl = (from TC in tabControl1.SelectedTab.Controls.OfType<TabControl>() select TC).FirstOrDefault();
    if (nestedTabControl != null && nestedTabControl.SelectedTab != null)
    {
        Control[] matches = nestedTabControl.SelectedTab.Controls.Find(dgvName, true);
        if (matches.Length > 0 && matches[0] is DataGridView)
        {
            DataGridView dgv = (DataGridView)matches[0];
            // ... do something with "dgv" ...
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM