的问题说,这一切,我想一个TableLayoutPanel添加到现有的Windows窗体,我已经试过这样:如何通过代码将元素添加到Windows窗体?
public class Level {
public TableLayoutPanel brickGrid;
public Level(Form parent, int width, int height, int left, int top, int rows, int columns) {
brickGrid = new TableLayoutPanel();
//Code
brickGrid.CellBorderStyle = TableLayoutPanelCellBorderStyle.InsetDouble;
//Code
brickGrid.SetAutoScrollMargin(2, 2);
brickGrid.BringToFront();
parent.Controls.Add(brickGrid);
}
}
但似乎没有工作:/
编辑: 这不是抛出任何崩溃,错误,异常或类似情况,网格不会显示出来。
下面是输出的图像: http://prntscr.com/9385e9
这里是全码:
namespace PingPong.Source {
public class Level {
public TableLayoutPanel brickGrid;
public Level(Form parent, int width, int height, int left, int top, int rows, int columns) {
brickGrid = new TableLayoutPanel();
brickGrid.Width = width;
brickGrid.Height = height;
brickGrid.Left = left;
brickGrid.Top = top;
brickGrid.CellBorderStyle = TableLayoutPanelCellBorderStyle.InsetDouble;
int originalRowCount = brickGrid.RowCount;
int originalColumnCount = brickGrid.ColumnCount;
float columnPercentage = 100f * columns/width;
float rowPercentage = 100f * rows/height;
int index = 0;
while (index <= columns) {
brickGrid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, columnPercentage));
index++;
}
index = 0;
while (index <= rows) {
brickGrid.RowStyles.Add(new RowStyle(SizeType.Percent, rowPercentage));
index++;
}
index = 0;
while (index < originalRowCount) {
brickGrid.RowStyles.RemoveAt(originalRowCount - index + 1);
index++;
}
index = 0;
while (index < originalColumnCount) {
brickGrid.ColumnStyles.RemoveAt(originalColumnCount - index + 1);
index++;
}
brickGrid.SetAutoScrollMargin(2, 2);
brickGrid.BringToFront();
parent.Controls.Add(brickGrid);
brickGrid.BackColor = System.Drawing.Color.Black;
}
}
}
它是如何工作的?你得到一个编译错误或异常?或者你看不到表单上的新元素? –
如果没有[良好,_minimal_,_complete_代码示例](http://stackoverflow.com/help/mcve)能够可靠地再现问题,并精确地解释了代码的作用以及与所需内容的不同之处,不可能知道你的问题的正确答案是什么。我将指出,一般来说,Winforms中的“面板”类型本身通常不会显示任何内容;你需要添加一些东西给他们看到。也许你需要做的只是添加一个孩子到你的'TableLayoutPanel'。 –
@YacoubMassad我只是看不到元素----------------------------- PeterDuniho:我已经添加了一些细节。网格应该可见,我猜想,因为我已经将边框添加到单元格中,并且它也具有背景颜色。无论如何,我会尝试一下,我如何添加一个孩子到网格?谢谢 –