views:

796

answers:

3

Hi guys. A simple one.

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?

+1  A: 

The method TabPages.Add will always put the page at the end of the collection. If you want to put them before the static added page use the Insert method instead

tabControl1.TabPages.Insert(0,tp);

This will put the new page, tp, first in the set of TabPages.

JaredPar
If you read carefully, my question says that the insert method is not working and I want to know why
vIceBerg
+7  A: 

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

tanascius
Thanks. Calling this resolved the problem.
vIceBerg
+1  A: 

You're passing the same index to the Insert() method. If you wish to simply increment, this should work:

// ...

int i = 0;
foreach (MyServiceConfigElement service in obj.Services)
            CreateServiceControl(service, i++);

// ...

private void CreateServiceControl(MyServiceConfigElement service, int i)
{
        TabPage tp = new TabPage(service.Name);
                tabControl1.TabPages.Insert(i, tp);
// ...

}
Bauer