0

I have TableLayoutPanel and adding rows dynamically. How can I insert the rows with controls at a specific index?

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;
  }
}

I tried

tableLayoutPanel1.RowStyles.Insert(0, newRowStyle);

but no luck

LarsTech
  • 80,625
  • 14
  • 153
  • 225
sangamesh
  • 11
  • 3
  • [Create dynamic buttons in a grid layout - Create a magic square UI](https://stackoverflow.com/q/33968993/3110834) – Reza Aghaei Jan 08 '19 at 16:05
  • Don't use a TableLayoutPanel where a DataGridView is more appropriate. – LarsTech Jan 08 '19 at 16:45
  • Above is just a sample code. My requirement is too complex which cannot be handled using DataGridView. So I am forced to use TableLayoutPanel – sangamesh Jan 09 '19 at 05:38

1 Answers1

1

There is no such function out of the box. The way is to add a row to your TableLayoutPanel. Then move all controls that are positioned in rows greater equal to your desired row index in a rowindex higher than their current position. Here how you can do that:

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);
        }
    }

}
Code Pope
  • 5,075
  • 8
  • 26
  • 68
  • I am not able to remove a row at given position. How can I remove it – sangamesh Jan 09 '19 at 07:21
  • @sangamesh Your question was how to insert a row in a specific index. Why do you want to remove a row? Or is it another question? – Code Pope Jan 09 '19 at 16:06
  • Yes. Its another question – sangamesh Jan 10 '19 at 04:51
  • @sangamesh Then you have either change the context and title of your question or mark this question as answered and open a new one. This will help other people if they refer to your question in the future. – Code Pope Jan 11 '19 at 11:40