Skip to main content
 首页 » 编程设计

c#之如何访问实时创建的TabPages

2024年02月20日11oomusou

代码中较早完成的一些初始化...

private List<System.Windows.Forms.TabPage> tab_pages = new List<System.Windows.Forms.TabPage>(); 
 
int tab_increment = 0; 

在代码的某处,我实时创建了一堆标签页。

for (i=0; i<5; i++) 
{ 
 
    tab_pages.Add(  new System.Windows.Forms.TabPage()  ); 
 
    tab_pages[tab_increment].Location = new System.Drawing.Point(4, 22); 
    tab_pages[tab_increment].Name = 1 + tab_increment.ToString(); 
    tab_pages[tab_increment].Size = new System.Drawing.Size(501, 281); 
    tab_pages[tab_increment].Text = tab_increment.ToString(); 
 
    this.tabControl.Controls.Add(tab_pages[tab_increment]); 
    tab_increment += 1; 
} 

现在我想访问这些标签页的元素。另外假设我在每个页面上创建了不同的元素(例如,tabPage[0] 一个按钮,tabPage[1] 一个复选框等),我如何在知道所有内容都是动态添加的情况下访问它们?

请您参考如下方法:

检查这个方法:

void Walk(Control control) 
{ 
    foreach (Control c in control.Controls) 
    { 
        //just walking through controls... 
        //...do something 
 
        //but remember, it could contain containers itself (say, groupbox or panel, etc.)...so, do a recursion 
        if (c.Controls.Count > 0) 
            Walk(c); 
 
    } 
    //or 
    foreach (Button btn in control.Controls.OfType<Button>()) 
    { 
        //an example of how to walk through controls sub array of certain type 
        //this loop won't have a single iteration if this page contains no Buttons 
 
        //..so you can replace Button  
        //and have some certain code for different types of controls 
    } 
} 

并为 tabcontrol 启动它:

foreach (TabPage page in tabControl1.TabPages) 
    Walk(page); 

我想没有特别需要为一个 tabcontrol 单独收集 tabpages,只要它有 TabPages 属性。

在上面的代码中我使用了 Enumerable.OfType Method 获取特定类型控件的子集合。


至于你的代码,试试这个:

for (int i = 0; i < 5; i++) 
{ 
    this.tabControl.Controls.Add(new System.Windows.Forms.TabPage()); 
    this.tabControl.TabPages[i].Text = i.ToString(); 
    //...do whatever you need 
    //... 
    //besdies, I think, ther's no need in tab_increment...loop index works well enough 
}