简体   繁体   English

tablelayoutpanel单元格未在c#win表单中均匀填充

[英]tablelayoutpanel cell not evenly padded in c# win forms

I have a tablelayoutpanel.And during run-time i am generating some labels dynamically, each having a purple round image.Now some images/labels are evenly padded inside each tablelayoutpanel cell but some are not.Please see the image.. 我有一个tablelayoutpanel.And在运行期间我动态生成一些标签,每个都有一个紫色圆形图像。现在每个tablelayoutpanel单元格内均匀填充一些图像/标签,但有些不是。请看图像.. 在此输入图像描述

Labels on the top 2 rows are evenly padded while rows starting form 3rd have shrunk. 顶部2行的标签均匀填充,而从第3行开始的行缩小。 Why is this happening? 为什么会这样? What need to be done to get rid of this problem?Thanks in advance. 需要做些什么来摆脱这个问题?提前谢谢。

You should set ColumnStyles and RowStyles to suitable values. 您应该将ColumnStylesRowStyles设置为合适的值。

For example for each column and row, you can define the style using SizeType.Percent or SizeType.Absolute and set an equal value for them. 例如,对于每个列和行,您可以使用SizeType.PercentSizeType.Absolute定义样式,并为它们设置相等的值。

In the below example: 在下面的例子中:

  • I set AutoSize property of TableLayoutPanel to true 我将TableLayoutPanel AutoSize属性设置为true
  • Set AutoScroll property of Form to true Form AutoScroll属性设置为true
  • Set column styles to SizeType.Percent using equal percent ( 100/columnCount ) 使用相等的百分比( 100/columnCount )将列样式设置为SizeType.Percent
  • Set row styles to SizeType.Absolute using equal vaules 30 组行样式SizeType.Absolute使用等于vaules 30
  • Add controls dynamically. 动态添加控件。

Sample Code: 示例代码:

int columnCount = 4;
int rowCount = 13;

this.tableLayoutPanel1.ColumnCount = columnCount;
this.tableLayoutPanel1.RowCount = rowCount;
this.tableLayoutPanel1.ColumnStyles.Clear();
this.tableLayoutPanel1.RowStyles.Clear();
this.tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
this.tableLayoutPanel1.BackColor = Color.White;
this.tableLayoutPanel1.AutoSize = true;

for (int i = 0; i < columnCount; i++)
{
    this.tableLayoutPanel1.ColumnStyles.Add(
        new ColumnStyle(SizeType.Percent, 100 / columnCount));
}
for (int i = 0; i < rowCount; i++)
{
    this.tableLayoutPanel1.RowStyles.Add(
        new RowStyle(SizeType.Absolute, 30));
}

this.tableLayoutPanel1.SuspendLayout();
for (var i = 1; i <= 50; i++)
{
    var label = new Label();
    label.Text = i.ToString();
    label.Font = new Font(label.Font, FontStyle.Bold);
    label.AutoSize = false;
    label.Size = new Size(30, 30);
    label.Image = Properties.Resources.Circle;
    label.ImageAlign = ContentAlignment.MiddleCenter;
    label.TextAlign = ContentAlignment.MiddleCenter;
    label.Dock = DockStyle.Fill;
    this.tableLayoutPanel1.Controls.Add(label);
}
this.tableLayoutPanel1.ResumeLayout();

Screenshot: 截图:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM