TableLayoutPanel sizing

前端 未结 3 1774
野趣味
野趣味 2021-01-04 11:41

I may not be using the right control for what I want. I\'m filling a table with controls and I want each column to automatically size to the controls contained within it. Fo

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 12:22

    Sorry, but what's wrong with having the columns set to Autosize? That's what TableLayoutPanel does, size columns to the fit the controls within it. Expanding the table and having a scrollbar would require you to set the tables Autosize property to true, then sit the TableLayoutPanel within another panel that has scrollbars enabled. But the column sizing should work out of the box if unless I'm misunderstanding your requirements.

    Just to make sure, you are going to the columns property and setting each column's SizeType to AutoSize right? Not just the AutoSize property of the table itself?

    enter image description here

    is this what you want?

    -Post code:

    Thanks for the code. I'd suggest that you use designer to do a lot of this. At least to set up the columns, set them to autosize, and add the heading labels.

    You also might want to check out the Datagrid control and bind that to your location list.

    To get this method working though:

    1) the reason your columns look the same size is because the heading labels you're using aren't autosizing. They're all x pixels wide and that's stretching the columns. Do this:

    Label lab = new Label();
    lab.AutoSize = true;
    lab.Text = "Location";
    tableLayoutPanel1.Controls.Add(lab, 0, 0);
    

    You'll also need to set the AutoSize property to true on the CheckBox control and any other labels you add as content.

    2) Setting the RowCount and ColumnCount won't affect the RowStyles or ColumnStyles collection. You've got 7 Columns but only 2 ColumnStyles. Try:

    tableLayoutPanel1.ColumnStyles.Clear();
    for (int i = 0; i < tableLayoutPanel1.ColumnCount; i++)
    {
       tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
    }
    
    tableLayoutPanel1.RowStyles.Clear();
    for (int i = 0; i < tableLayoutPanel1.RowCount; i++)
    {
       tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.AutoSize));
    }
    

    Only other thing to look out for is that some controls will be misaligned in the rows (labels appear too high for example). To fix that set the Margin property, normally to 3,6,3,0 to align them with textboxes and checkboxes etc.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题