How can i programmatically add a Tab to a form during runtime?

若如初见. 提交于 2019-12-31 05:31:05

问题


I googled this and still cant get it to work. I know how to add a tab using the toolbox. I have also read about how to do it programmatically, but i still dont get it. (MSVC# Express 2010)

I have an easy project set up. Just a windows Form with a TabControl in it, i used the Designer to add a new TabControl and made that TabControl public instead of private.

I wrote this code to a) access the Windows Form b) add a tabpage.

The code compiles just fine, but the Tabpage is not displayed during runtime.

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Form1 ApplicationMainForm = new Form1();
        Application.Run(ApplicationMainForm); //LABEL B

        ApplicationMainForm.tabControl1.TabPages.Add("MyPage"); //LABEL A
    }
}

How can i get the form to display my Tabpage? My TabPage is displayed when the Lines A and B change position. Am i missing an update method, oder is the TabPage Add never called until the application closes?

Edit #1: Some minor edits. Edit #2: Edited in some more examplecode. Edit #3: Removed some earlier / irelevant points. Edit #4: Found a hint and edited this information in


回答1:


Form1.tabControl1.Controls.Add(myNewTabItem);

The tab control is a collection of tab pages, so you add tab pages like you add any control to a collection. Note that the tabs show up in the order you add them.




回答2:


If you are trying to add a tab to the form at runtime, probably the issue is that you are trying to adjust the form definition instead of the specific instance of that form that you are currently displaying. When a form is opened, it is an instance of the form definition. You have to find that instance in order to modify its properties. Therefore, you would have to have the other part of your program somehow know about that particular instance of your form through something like a reference variable.



来源:https://stackoverflow.com/questions/5858017/how-can-i-programmatically-add-a-tab-to-a-form-during-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!