FernandoPaiva FernandoPaiva - 2 months ago 15
C# Question

How to create columns dynamic with TableLayoutPanel?

I added a TableLayoutPanel into a form, and now I'm trying create columns dynamic to add buttons in this TableLayoutPanel. The problem is that only one column has been created and display only one button.

How could I do this ?

Trying.

private void findAllCategorias() {
IList<CategoriaProduto> _lista = cDAO.findAll();
int count = 0;
foreach (CategoriaProduto x in _lista) {
Button b = new Button();
b.Name = Convert.ToString(x.id);
b.Text = x.descricao;
b.Size = new Size(100,65);
b.Click += new EventHandler(btnCategoria_Click);
b.BackColor = Color.FromArgb(255,255,192);
ToolTip tt = new ToolTip();
tt.SetToolTip(b, Convert.ToString(x.id));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
panel.Controls.Add(b, count++, 0);
}
}


I want this result

enter image description here

Answer

Adding a ColumnStyle is not enough (actually it's optional), you need also to increment the ColumnCount property:

// ...
panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize));
panel.ColumnCount++;
panel.Controls.Add(b, count++, 0);                
// ...