簡體   English   中英

如何訪問實時創建的TabPages?

[英]How to access TabPages that are created in real-time?

一些在代碼中早先完成的內容......

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]一個復選框等),如何知道所有內容都是動態添加的?

為了添加頁面,我認為使用

tabControl.TabPages.Add(new TabPage("Name"));

或者在你的情況下

this.tabControl.TabPages.Add(tab_pages[tab_increment]);

更合適。

為了訪問它們,您可以使用

TabPage tp = tabControl.TabPages[i];  //where i is the index of your TabPage

並且您可以使用Controls屬性的TabPage.Controls.AddTabPage上添加任何Control ,如:

Button btn = new Button();
btn.Name = "Button name";
tp.Controls.Add(btn);

檢查這種方法:

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方法來獲取某些類型的控件的子集合。


至於你的代碼,試試這個:

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
}

您可以在TabPage對象上使用Controls屬性。 集合中的每個控件都作為Control提供給您,您可以將它們轉換為所需的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM