【问题标题】:How do I apply column and row styles on a TableLayoutPanel programmatically?如何以编程方式在 TableLayoutPanel 上应用列和行样式?
【发布时间】:2016-08-02 15:18:28
【问题描述】:

一开始有一个只有一行没有列的 TableLayoutPanel。通过按一个按钮,我希望这个面板变成 5 行 3 列

private void button_Click(object sender, EventArgs e)
    {
        this.tableLayoutPanel1.ColumnCount = 3;
        this.tableLayoutPanel1.RowCount = 5;
    }

问题是你得到了这个结果!

如您所见,使用行和列创建的框在面板中不包含相同的区域。

在 3 列和 5 行的情况下,列必须共享 100% 的 tablelayoutpanel,因此每个列 30%。 5行的情况下,每行必须占20%。

所以我将接下来的两行代码附加到 button_Click 方法。

this.tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
this.tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 20F));

但是我得到了同样的结果! 我错过了什么?

【问题讨论】:

  • 为什么需要空的TableLayoutPanel?只需为其添加控件(请参阅this answer)。屏幕截图与您的代码不匹配。考虑准备mcve(以分步指南或Form1.cs + Form1.designer.cs的完整转储的形式),然后有人可能会尝试更仔细地研究您的问题。

标签: c# winforms tablelayoutpanel


【解决方案1】:

您可能正在向已定义的 TableLayoutPanel 添加样式而不重置当前样式。

tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
tableLayoutPanel1.Dock = DockStyle.Fill;

tableLayoutPanel1.Controls.Clear();
tableLayoutPanel1.ColumnStyle.Clear();
tableLayoutPanel1.RowStyle.Clear();

tableLayoutPanel1.RowCount = 5;
for(int x = 0; x < tableLayoutPanel1.RowCount; x++)
    tableLayoutPanel1.RowStyles.Add(new RowStyle() { Height = 20, SizeType = SizeType.Percent });
tableLayoutPanel1.ColumnCount = 3;
for(int x = 0; x < tableLayoutPanel1.ColumnCount; x++)
    tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle() { Width = 33, SizeType = SizeType.Percent });

【讨论】:

  • 先生。史蒂夫,非常感谢你!这只是节省我的一天。
猜你喜欢
  • 1970-01-01
  • 2010-11-11
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多