如何使用 TableLayoutPanel 动态创建列?

How to create columns dynamic with TableLayoutPanel?

我在表单中添加了一个 TableLayoutPanel,现在我正在尝试动态创建列以在此 TableLayoutPanel 中添加按钮。问题是只创建了一列并且只显示一个按钮。

我该怎么做?

正在尝试。

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

我要这个结果

添加 ColumnStyle 是不够的(实际上它是可选的),您还需要增加 ColumnCount 属性:

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