2013-06-04 30 views
1

我正在开发一个Windows应用程序,我想在循环内动态创建一些控件。 我想要的代码是在C#中循环动态添加控件

private Label newLabel = new Label(); 
private int txtBoxStartPosition = 100; 
private int txtBoxStartPositionV = 25; 

for (int i = 0; i < 7; i++) 
{ 

    newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV); 
    newLabel.Size = new System.Drawing.Size(70, 40); 
    newLabel.Text = i.ToString(); 

    panel1.Controls.Add(newLabel); 
    txtBoxStartPositionV += 30; 


} 

此代码生成只有一个标签与文本7,但我想创建8个标贴各自的文本,我该怎么办呢?

回答

1

您需要在for循环中放置行private Label newLabel = new Label();

private int txtBoxStartPosition = 100; 
private int txtBoxStartPositionV = 25; 

for (int i = 0; i < 7; i++) 
{ 
    Label newLabel = new Label(); 
    newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV); 
    newLabel.Size = new System.Drawing.Size(70, 40); 
    newLabel.Text = i.ToString(); 

    panel1.Controls.Add(newLabel); 
    txtBoxStartPositionV += 30; 
} 
+0

这不会编译。 – Arran

+0

按照示例从行中删除'private'。 –

+0

你没有那么开始;) – Arran

2

试试这个:

private int txtBoxStartPosition = 100; 
private int txtBoxStartPositionV = 25; 

for (int i = 0; i < 7; i++) 
{ 
    newLabel = new Label(); 
    newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV); 
    newLabel.Size = new System.Drawing.Size(70, 40); 
    newLabel.Text = i.ToString(); 

    panel1.Controls.Add(newLabel); 
    txtBoxStartPositionV += 30; 


} 
+0

非常感谢!它工作 – Hanumendra

4

在你的循环,你基本上是更新非常相同标签的属性。如果你想创建每一步一个新的,移动对象的创建循环中:

private Label newLabel; 

for (int i = 0; i < 7; i++) 
{ 
    newLabel = new Label(); 
    ... 

通过,如果你想标签的方式 - 你for应该重复8次,而不是7,因为它现在做:

for (int i = 0; i < 8; i++) 
+0

非常感谢!有效 – Hanumendra