Search code examples
c#winformsdynamictablelayoutpanel

How can I programmatically set the Column and Row properties of controls that are dynamically created to embed within a TableLayoutPanel?


When I drop a control, such as a Label or a TextBox, on a TableLayoutPanel, it has (among many others, of course) the following properties:

Cell.Column
Cell.Row
Column
Row

...but these controls don't normally have these properties (IOW, Labels and TextBoxes that are not dropped on the TLP do not have them).

How can I programmatically assign values to these properties (to controls I want to embed within a TLP)?

This is my existing code for the Labels:

. . .
lblName = string.Format("label{0}", i);
var lbl = new Label()
{
    Name = lblName,
    Parent = tableLayoutPanelPlatypi,
    Column = ColNum, // Doesn't compile; Column property not recognized
    Row = i - 1,     // Doesn't compile; Row property not recognized
    Dock = DockStyle.Fill,
    Margin = 0,
    TextAlign = ContentAlignment.MiddleCenter,
    Text = GettysburgAddressObfuscation()
};

Solution

  • You can add them via the TableLayoutPanel's controls Add method:

    tableLayoutPanelPlatypi.Controls.Add(lbl, ColNum, i - 1);
    

    or as you pointed out, each property can be set individually:

    tableLayoutPanelPlatypi.SetColumn(lbl, ColNum);
    tableLayoutPanelPlatypi.SetRow(lbl, i - 1);
    

    The Form's Designer is adding those properties conveniently for you, but if you look inside the designer file at a control that has been added to the TableLayoutPanel, it uses that format above.