我在TabControl1中有一个TabControl2。 TabControl2位于TabControl1的所有TabPages中。 TabControl2的TabPage是DataGridView,我需要使用这个DataGridView工作(Add.Rows等)。全部以编程方式添加。
我正在寻找找到合适的DataGridView的最佳方法,所以我需要这样的东西:
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
}
答案 0 :(得分:1)
此Linq查询返回嵌套DataGridView
中的第一个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) ...
答案 1 :(得分:0)
我认为最直接的方法是:
tabControl1.Controls.Find("data_grid_view_name", true);
答案 2 :(得分:0)
另一个例子:
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" ...
}
}
}