首页 > 解决方案 > 在给定索引处将行添加到 TableLayoutPanel

问题描述

我有 TableLayoutPanel 并动态添加行。如何在特定索引处插入带有控件的行?

private void AddRowstoTableLayout()
{
  for (int cnt = 0; cnt < 5; cnt++)
  {
    RowStyle newRowStyle = new RowStyle();
    newRowStyle.Height = 50;
    newRowStyle.SizeType = SizeType.Absolute;

    Label lbl1 = new Label();
    lbl1.Text = "label-" + (cnt + 1);

    TextBox t1 = new TextBox();
    t1.Text = "text-" + (cnt + 1);

    Label lblMove = new Label();
    lblMove.Text = "Move-" + (cnt + 1);
    lblMove.MouseDown += new MouseEventHandler(dy_MouseDown);

    tableLayoutPanel1.RowStyles.Insert(0, newRowStyle);
    this.tableLayoutPanel1.Controls.Add(lbl1, 0, cnt); //correct

    this.tableLayoutPanel1.Controls.Add(t1, 1, cnt); //correct
    this.tableLayoutPanel1.Controls.Add(lblMove, 2, cnt); //correct
    tableLayoutPanel1.RowCount += 1;
  }
}

我试过了

tableLayoutPanel1.RowStyles.Insert(0, newRowStyle);

但没有运气

标签: c#winformstablelayoutpanel

解决方案


开箱即用没有这样的功能。方法是向您的 TableLayoutPanel 添加一行。然后将位于大于等于所需行索引的行中的所有控件移动到高于其当前位置的行索引中。在这里你可以如何做到这一点:

void InsertTableLayoutPanelRow(int index)
{
    RowStyle newRowStyle = new RowStyle();
    newRowStyle.Height = 50;
    newRowStyle.SizeType = SizeType.Absolute;

    tableLayoutPanel1.RowStyles.Insert(index, newRowStyle);
    tableLayoutPanel1.RowCount++;
    foreach (Control control in tableLayoutPanel1.Controls)
    {
        if (tableLayoutPanel1.GetRow(control) >= index)
        {
            tableLayoutPanel1.SetRow(control, tableLayoutPanel1.GetRow(control) + 1);
        }
    }

}

推荐阅读