Cod*_*roc 33 .net c# tablelayoutpanel

我想在c#中的Windows窗体中的TableLayoutPanel中逐行动态添加这些条目
我怎样才能做到这一点?
pet*_*jan 59
试试下面的代码,
// TableLayoutPanel Initialization
TableLayoutPanel panel = new TableLayoutPanel();
panel.ColumnCount = 3;
panel.RowCount = 1;
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 40F));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));
panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));
panel.Controls.Add(new Label() { Text = "Address" }, 1, 0);
panel.Controls.Add(new Label() { Text = "Contact No" }, 2, 0);
panel.Controls.Add(new Label() { Text = "Email ID" }, 3, 0);
// For Add New Row (Loop this code for add multiple rows)
panel.RowCount = panel.RowCount + 1;
panel.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));
panel.Controls.Add(new Label() { Text = "Street, City, State" }, 1, panel.RowCount-1);
panel.Controls.Add(new Label() { Text = "888888888888" }, 2, panel.RowCount-1);
panel.Controls.Add(new Label() { Text = "xxxxxxx@gmail.com" }, 3, panel.RowCount-1);
Run Code Online (Sandbox Code Playgroud)
ted*_*bus 17
我知道这个问题已经很老了,但是有人可以把它作为有用的东西.
首先要注意petchirajan的答案是好的,但是如果你有至少一个现有的行(例如标题)并且你想使用可视编辑器使用高度设置继续列表,而不修改代码,你可以使用:
private void AddItem(string address, string contactNum, string email )
{
//get a reference to the previous existent
RowStyle temp = panel.RowStyles[panel.RowCount - 1];
//increase panel rows count by one
panel.RowCount++;
//add a new RowStyle as a copy of the previous one
panel.RowStyles.Add(new RowStyle(temp.SizeType, temp.Height));
//add your three controls
panel.Controls.Add(new Label() {Text = address}, 0, panel.RowCount - 1);
panel.Controls.Add(new Label() { Text = contactNum }, 1, panel.RowCount - 1);
panel.Controls.Add(new Label() { Text = email }, 2, panel.RowCount - 1);
}
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢泛型表的泛型方法:
private void AddRowToPanel(TableLayoutPanel panel, string[] rowElements)
{
if (panel.ColumnCount != rowElements.Length)
throw new Exception("Elements number doesn't match!");
//get a reference to the previous existent row
RowStyle temp = panel.RowStyles[panel.RowCount - 1];
//increase panel rows count by one
panel.RowCount++;
//add a new RowStyle as a copy of the previous one
panel.RowStyles.Add(new RowStyle(temp.SizeType, temp.Height));
//add the control
for (int i = 0; i < rowElements.Length; i++)
{
panel.Controls.Add(new Label() { Text = rowElements[i] }, i, panel.RowCount - 1);
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用Collection而不是使用数组来执行此操作
private void AddRowToPanel(TableLayoutPanel panel, IList<string> rowElements)
...
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你.
| 归档时间: |
|
| 查看次数: |
72535 次 |
| 最近记录: |