TableLayoutPanel column widths at runtime: strange behavior or bug

Run CMD picture Run CMD · Apr 21, 2011 · Viewed 14.9k times · Source

I have a tableLayoutPanel with either 5 or 7 columns. Users can click "show/hide weekend" button to switch from 5 to 7 days.

The problem : When you start with 5 days, then press the 5/7 button, the 7 columns are NOT spaced evenly ... column 6 is much smaller then the rest. The strange thing is that if you start with 7 days, all looks ok. When you switch to 5 and then back to 7, still all is fine ??

    void lblSatSunday_Click(object sender, EventArgs e)
    {
        ShowZaterdagZondag = !ShowZaterdagZondag;
        AddDisplayControls();
    }

    private void AddDisplayControls()
    {
        tblPanel.SuspendLayout();
        tblPanel.Controls.Clear();
        tblPanel.ColumnCount = ShowZaterdagZondag ? 7 : 5; // <<<-------
        tblPanel.RowCount = 1;
        tblPanel.GrowStyle = TableLayoutPanelGrowStyle.FixedSize;//.AddColumns;
        for (int i = 0; i < tblPanel.ColumnCount; i++)
        {
            ColumnStyle cs = new ColumnStyle(SizeType.Percent, 100 / tblPanel.ColumnCount);
            tblPanel.ColumnStyles.Add(cs);

            //Add accordeon
            Accordeon a = new Accordeon();
            //Removed code for reading
            tblPanel.Controls.Add(a);
        }
        tblPanel.ResumeLayout();
    }

Answer

Hans Passant picture Hans Passant · Apr 21, 2011

Add this line of code before the for loop:

 tblPanel.ColumnStyles.Clear();