Search code examples
c#winformsautoscrolltablelayoutpanel

Disable TableLayoutPanel rows autoscaling


I want to disable rows autoscaling of TableLayoutPanel so that it would fit, for example, 4 columns on width and 3 rows on height and autoscrolling also would work. What should I change?

Code:

    public UserControl()
    {
        InitializeComponent();
        tableLayoutPanel1.ColumnStyles.Clear();
        tableLayoutPanel1.RowStyles.Clear(); 
        foreach (Picture picture in Program.gallery)
            addImage(picture);
        for (int i=0;i<tableLayoutPanel1.ColumnCount;i++)
            tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f/4));
        for (int i = 0; i < 99999; i++)
            tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100f/3));
    }

TableLayoutPanel has:

AutoScroll=true;
AutoSize=false;
ColumnCount=4;
RowCount=3;
Dock=true;
GrowStyle=AddRows;

Solution

  • Percent size type is broken. Scrollbar of TableLayoutPanel is also glitchy and is not shrink. Here

    I used these properites for table:

    AutoScroll=false;
    AutoSize=true;
    ColumnCount=4;
    RowCount=0;
    Dock=Top;
    GrowStyle=AddRows;
    

    and external control property:

    AutoScroll=true;
    

    Code for checking rows count and disabling unused:

    private int cellsCount=0;
    private const int rows = 3;
    private int CellsCount {
            get => cellsCount;
            set { 
                cellsCount = value;
                int expectedRows = (cellsCount - 1 + tableLayoutPanel1.ColumnCount) / tableLayoutPanel1.ColumnCount;
                while (expectedRows > tableLayoutPanel1.RowCount)
                {
                    tableLayoutPanel1.RowCount++;
                    tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, Height/rows));
                }
                while (expectedRows < tableLayoutPanel1.RowCount) {
                    tableLayoutPanel1.RowCount--;
                    tableLayoutPanel1.RowStyles.RemoveAt(0);
                }
            }
    }
    

    And resize listener to set true dimensions of rows:

    private void tableLayoutPanel1_Resize(object sender, EventArgs e)
    {
        foreach (RowStyle row in tableLayoutPanel1.RowStyles)
            row.Height = Height / rows;
    }