仅在动态填充单元格时调整 TableLayoutPanel 行的大小

Resize TableLayoutPanel rows only as cells are dynamically populated

我有一个 TableLayoutPanel,ug_degrees,有 3 列和 1 行。每个单元格都动态填充了另一个 TableLayoutPanel degreePanel,其中包含 1 个标签和 1 个文本框。

我需要让我的布局看起来像这样:

现在我的布局是这样的:

我不知道为什么我的单元格之间有那么大的空隙,为什么该行不会扩展以填充其内容(标签和文本框)。我试图将整个 TableLayoutPanel 的自动调整大小 属性 设置为 true,但列会调整大小,即使我也只将行的 sizetype 设置为自动调整大小。

显示的table后面的属性是默认的。所有非默认属性都在下面的 C# 中自定义。

// Dynamically load undergraduate degrees
int row = 0;
for (int i = 0; i < degrees.undergraduate.Count; i++) {
    // Create and populate panel for each degree
    TableLayoutPanel degreePanel = new TableLayoutPanel();
    degreePanel.ColumnCount = 1;
    degreePanel.RowCount = 2;
    degreePanel.AutoSize = true;
    foreach (RowStyle style in degreePanel.RowStyles) {
        style.SizeType = SizeType.AutoSize;
    }
    degreePanel.BorderStyle = BorderStyle.FixedSingle;
    //degreePanel.Margin = new Padding(0);

    Label degTitle = new Label();
    degTitle.Text = degrees.undergraduate[i].title;
    degTitle.Dock = DockStyle.Fill;

    TextBox degDesc = new TextBox();
    degDesc.ReadOnly = true;
    degDesc.Multiline = true;
    degDesc.Dock = DockStyle.Fill;
    degDesc.Text = degrees.undergraduate[i].description;
    SizeF size = degDesc.CreateGraphics()
                .MeasureString(degDesc.Text,
                                degDesc.Font,
                                degDesc.Width,
                                new StringFormat(0));
    degDesc.Height = (int)size.Height;

    degreePanel.Controls.Add(degTitle, 0, 0);
    degreePanel.Controls.Add(degDesc, 0, 1);
    ug_degrees.Controls.Add(degreePanel, i, row);

    // Resize rows and columns (only after adding controls)
    foreach (RowStyle style in ug_degrees.RowStyles) {
        style.SizeType = SizeType.AutoSize;
    }

    // Jump to next row if current row is full
    if ((i+1) % 3 == 0) {
        row++;
    }

添加degreePanel.Dock = DockStyle.Fill