Search code examples
c#winformsdynamictablelayoutpanel

Why does 12 X 8.33 seem to equate to about 105?


In my TableLayoutPanel, I'm dynamically adding twelve rows (and several columns). When I had the TableLayoutPanel's Rows collection set to Autosize, the 12th row would be generated, but would not display. I changed it to Percentage, with each row getting 8.33% (I actually set it to 8, and it was automatically changed to 8.33).

So that should be perfect to the naked eye (99.99999999%), but now the twelfth row has more space than the others, and the 16th column the same, so the TableLayoutPanel has "dead space" at the bottom and right, and the labels I have in the final row are not aligned with the textBoxes I have in the neighboring column.

In case anybody's interested in seeing the actual code:

private void AddControlsToPlatypusTableLayoutPanel()
{
    string lblName;
    string txtbxName;
    int ColNum = 0;
    int RowNum = 0;
    int LoopCounter = 1;
    DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);

    while (LoopCounter <= 96) {
        // Create the Label
        lblName = string.Format("label{0}", LoopCounter);
        var lbl = new Label() {
            Name = lblName,
            Dock = DockStyle.Fill,
            Margin = new Padding(),
            TextAlign = ContentAlignment.MiddleCenter,
            Text = dt.ToString("HH:mm")
        };
        tableLayoutPanelPlatypus.Controls.Add(lbl, ColNum, RowNum);

        // Create the TextBox
        txtbxName = string.Format("textBox{0}", LoopCounter);
        var txtbx = new TextBox() {
            Name = txtbxName, Dock = DockStyle.Fill, Margin = new Padding()
        };
        tableLayoutPanelPlatypus.Controls.Add(txtbx, ColNum + 1, RowNum);

        dt = dt.AddMinutes(15);
        RowNum++;
        LoopCounter++;
        // Move over if at the bottom
        if (RowNum == 12) { 
            ColNum = ColNum + 2;
            RowNum = 0;
        }
    }
}

UPDATE

By tweaking the Size and Location a smidgin, I can get it all to look good, but now I either have to live with a cushion around it or change the size of the form and all the other controls, or many of them, anyway. So I still consider it a bit irregular that the percentages didn't work out as one would expect them to. I know, I know: WPF. But that's not an option at present.


Solution

  • if you have set it to 8 then 8*12 conclude to 84% with 16% remaining which will be accommodated in last row as well same case applies to last column. So you need to define it to 100/12 = 8.33%. if you made each row with 8.33% and last row with 8.37% this will look nice. you need to complete 100% in both case of rows or columns. or you can use fix size instead. if you want variable size of table then be sure you do not define size of table and rows height and columns width define table size dynamically.