Search code examples
c#winformstablelayoutpanel

Issue with column sizes using TableLayoutPanel


I have the following code:

        var tlp = new TableLayoutPanel
                      {
                          Location = new Point(0, 0),
                          Name = "TableLayoutPanel1",
                          Dock = DockStyle.Fill,
                          BackColor = Color.White,
                          TabIndex = 0
                      };

        Controls.Add(tlp);

        tlp.RowStyles.Add(new RowStyle(SizeType.Absolute, 14f));
        tlp.RowStyles.Add(new RowStyle(SizeType.Absolute, 18f));
        tlp.RowStyles.Add(new RowStyle(SizeType.Absolute, 12f));
        tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 100f));
        tlp.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute,  50f));

        var label3 = new Label
        {
            Font = new Font("Tahoma", 8, FontStyle.Regular),
            Text = Description,
            AutoSize = false,
            Width=50,
            ForeColor = Color.Black,
            TextAlign = ContentAlignment.TopLeft
        };
        tlp.Controls.Add(label3, 1, 2);

My problem is, when I run my application, there is nothing displayed. If I change the last line to display in the first column, like so:

        tlp.Controls.Add(label3, 0, 2);

Then it shows up just fine in the first column. Also, if I change my ColumnStyle definition to SizeType.Percentage instead of Absolute, that works fine too, but I don't want a percentage, I want a 100 pixel fixed column on the left and a 50 pixel fixed column on the right.

Can someone point me into the right direction on this?


Solution

  • You have to also set the RowCount and ColumnCount properties. Strange, I know.

    So:

    tlp.RowCount = 3;
    tlp.ColumnCount = 2;