我上周刚做过。设置GrowStyle
上TableLayoutPanel
以AddRows
或AddColumns
,那么你的代码应工作:
myTableLayoutPanel.Controls.Add(myControl1, 0 , 0 );
myTableLayoutPanel.Controls.Add(myControl2, 0 , 1 );
myTableLayoutPanel.Controls.Add(myControl3, 0 , 2 );
这是一些似乎与您正在执行的工作代码类似的代码:
private Int32 tlpRowCount = 0;
private void BindAddress()
{
Addlabel(Addresses.Street);
if (!String.IsNullOrEmpty(Addresses.Street2))
{
Addlabel(Addresses.Street2);
}
Addlabel(Addresses.CityStateZip);
if (!String.IsNullOrEmpty(Account.Country))
{
Addlabel(Address.Country);
}
Addlabel(String.Empty);
}
private void Addlabel(String text)
{
label = new Label();
label.Dock = DockStyle.Fill;
label.Text = text;
label.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
tlpAddress.Controls.Add(label, 1, tlpRowCount);
tlpRowCount++;
}
该TableLayoutPanel
总是给我用一刀切。在上面的示例中,我要提交的地址卡可能会增加或缩小,具体取决于拥有第二行地址的帐户或国家/地区。因为表格布局面板的最后一行或最后一列会拉伸,所以我在其中放置了空标签以强制添加新的空行,然后所有内容都很好地对齐了。
这是设计器代码,因此您可以看到我开始的表格:
this.tlpAddress.AutoSize = true;
this.tlpAddress.BackColor = System.Drawing.Color.Transparent;
this.tlpAddress.ColumnCount = 2;
this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 25F));
this.tlpAddress.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tlpAddress.Controls.Add(this.pictureBox1, 0, 0);
this.tlpAddress.Dock = System.Windows.Forms.DockStyle.Fill;
this.tlpAddress.Location = new System.Drawing.Point(0, 0);
this.tlpAddress.Name = "tlpAddress";
this.tlpAddress.Padding = new System.Windows.Forms.Padding(3);
this.tlpAddress.RowCount = 2;
this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlpAddress.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tlpAddress.Size = new System.Drawing.Size(220, 95);
this.tlpAddress.TabIndex = 0;