DeepSpace
DeepSpace

Reputation: 81594

C# WinForms, Adding tabs to a tab control, then adding a control to each tab programmatically

I have a form that should iterate over a list, and for each item in the list add a tab to a tab control. Then, I have a Group Box that should be added to each tab.

The tabs are added fine, but the Group Box is only added to the last tab (also the debugger shows that every tab's Controls collection is empty, except for the last tab).

Any insights?

foreach (String company in requiredGasComps)
{
   tabCont.TabPages.Add(company,company);     
}

foreach (TabPage tabpage in tabCont.TabPages)
{
   tabpage.Controls.Add(groupBox);
}


foreach ( TabPage tabpage in tabCont.TabPages)
{
    Control [] a = tabpage.Controls.Find("currentSupplier95",true);

    //Will always find 0 or 1 control
    if (a.Length > 0)
    {
        a[0].Text = tabpage.Text;
    }
}

this.Controls.Add(tabCont); 

Upvotes: 1

Views: 4445

Answers (4)

DeepSpace
DeepSpace

Reputation: 81594

Thanks all, I ended up creating a User Control, then

foreach (TabPage tabpage in tabCont.TabPages)
{
    EnergyTable table = new EnergyTable();
    tabpage.Controls.Add(table);
}

Works like a charm.

Upvotes: 0

Sayse
Sayse

Reputation: 43300

I would recommend modifying your code to create a tabpage to add and then you can add the group box at the same time

foreach (String company in requiredGasComps)
{
    TabPage t = new TabPage(){Name = company, Text = company};
    Groupbox gb = groupBox.CreateNewBasedFromThis();
    t.Controls.Add(gb);
    tabCont.TabPages.Add(t);     
}

This would also be more efficient since you don't have to iterate twice

You can create an extension method too to create a new groupbox based off the old one

public static GroupBox CreateNewBasedFromThis(this GroupBox gb)
{
    var newGb = new GroupBox;
    //set new properties that you wish to copy
    return newGb;
}

Upvotes: 1

MatteoSp
MatteoSp

Reputation: 3048

A control can belong to only one collection, or - in other words - can have only one father. So you can't add the same GroupBox to multiple tabs, you have to create different GroupBox instances and then add them to the tabs.

Upvotes: 1

HeadShotSmiley
HeadShotSmiley

Reputation: 21

I think you put the same groupBox on every Tabpage. Try:

foreach (TabPage tabpage in tabCont.TabPages)
{
   GroupBox groupBox = new GroupBox();
   tabpage.Controls.Add(groupBox);
}

Upvotes: 1

Related Questions