Add Row Dynamically in TableLayoutPanel
I know that this question is very old, but someone could find the following as useful:
First of all, note that petchirajan's answer is good, but if you have at least one existent row (titles, for example) and you want to continue the list using the height set using visual editor, and without having to modify the code, you can use this:
private void AddItem(string address, string contactNum, string email )
{
//get a reference to the previous existent
RowStyle temp = panel.RowStyles[panel.RowCount - 1];
//increase panel rows count by one
panel.RowCount++;
//add a new RowStyle as a copy of the previous one
panel.RowStyles.Add(new RowStyle(temp.SizeType, temp.Height));
//add your three controls
panel.Controls.Add(new Label() {Text = address}, 0, panel.RowCount - 1);
panel.Controls.Add(new Label() { Text = contactNum }, 1, panel.RowCount - 1);
panel.Controls.Add(new Label() { Text = email }, 2, panel.RowCount - 1);
}
If you prefer a generic method for a generic table:
private void AddRowToPanel(TableLayoutPanel panel, string[] rowElements)
{
if (panel.ColumnCount != rowElements.Length)
throw new Exception("Elements number doesn't match!");
//get a reference to the previous existent row
RowStyle temp = panel.RowStyles[panel.RowCount - 1];
//increase panel rows count by one
panel.RowCount++;
//add a new RowStyle as a copy of the previous one
panel.RowStyles.Add(new RowStyle(temp.SizeType, temp.Height));
//add the control
for (int i = 0; i < rowElements.Length; i++)
{
panel.Controls.Add(new Label() { Text = rowElements[i] }, i, panel.RowCount - 1);
}
}
You can do this also using a Collection instead of an array using:
private void AddRowToPanel(TableLayoutPanel panel, IList<string> rowElements)
...
Hope this helps.
Try the below code,
// TableLayoutPanel Initialization
TableLayoutPanel panel = new TableLayoutPanel();
panel.ColumnCount = 3;
panel.RowCount = 1;
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40F));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));
panel.Controls.Add(new Label() { Text = "Address" }, 1, 0);
panel.Controls.Add(new Label() { Text = "Contact No" }, 2, 0);
panel.Controls.Add(new Label() { Text = "Email ID" }, 3, 0);
// For Add New Row (Loop this code for add multiple rows)
panel.RowCount = panel.RowCount + 1;
panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));
panel.Controls.Add(new Label() { Text = "Street, City, State" }, 1, panel.RowCount-1);
panel.Controls.Add(new Label() { Text = "888888888888" }, 2, panel.RowCount-1);
panel.Controls.Add(new Label() { Text = "[email protected]" }, 3, panel.RowCount-1);