Visual studio - TabControl.TabPages.Insert not working

vIceBerg picture vIceBerg · Oct 7, 2009 · Viewed 7.6k times · Source

Here's my code:

    public MainForm()
    {
        InitializeComponent();

        MyServiceSettings obj = (MyServiceSettings)ConfigurationManager.GetSection("MyServiceSettings");

        foreach (MyServiceConfigElement service in obj.Services)
            CreateServiceControl(service);
    }

    private void CreateServiceControl(MyServiceConfigElement service)
    {
        TabPage tp = new TabPage(service.Name);
        tabControl1.TabPages.Insert(0, tp);
        //tabControl1.TabPages.Add(tp);
        tabControl1.Refresh();    
    }

In a nutshell, it reads a section in a config file and creates a tab for each element in the section.

I already have one static TabPage created at design time. I want the dynamic created tabs to be inserted before this static tab.

Running this code, the tabcontrol shows only the static tabpage.

If I do this change:

        private void CreateServiceControl(SoftInfoServiceConfigElement service)
    {
        TabPage tp = new TabPage(service.Name);
        //tabControl1.TabPages.Insert(1, tp);
        tabControl1.TabPages.Add(tp);
        tabControl1.Refresh();
    }

Using the Add method shows all the pages. But I do not get the order I want.

Is there something I don't understand with the Insert method? Why is it'n working?

Answer

tanascius picture tanascius · Oct 7, 2009

There is a comment on social.msdn - although I could not find anything like this in the documentation:

The TabControl's handle must be created for the Insert method to work

Try the mentioned code

IntPtr h = this.tabControl1.Handle;

before you loop over your services