我上周刚做了这件事。将TableLayoutPanel
上的GrowStyle
设置为AddRows
或AddColumns
,然后你的代码应该就能正常工作:
// Adds "myControl" to the first column of each row
myTableLayoutPanel.Controls.Add(myControl1, 0 /* Column Index */, 0 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl2, 0 /* Column Index */, 1 /* Row index */);
myTableLayoutPanel.Controls.Add(myControl3, 0 /* Column Index */, 2 /* Row index */);
这里有一些可行的代码,看起来与您正在做的类似:
private Int32 tlpRowCount = 0;
private void BindAddress()
Addlabel(Addresses.CityStateZip);
if (!String.IsNullOrEmpty(Account.Country))
Addlabel(String.Empty);
}
private void Addlabel(String text)
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;