3

我正在开发一个 Windows 应用程序,我想在循环中动态创建一些控件。我正在尝试的代码是

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 个带有各自文本的标签,我该怎么做?

4

3 回答 3

4

在您的循环中,您实际上是在更新同一个标签的属性。如果要在每个步骤上创建一个新对象,请在循环内移动对象的创建:

private Label newLabel;

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

顺便说一句,如果你想要8个标签 - 你for应该迭代 8 次,而不是 7 次,就像现在这样:

for (int i = 0; i < 8; i++)
于 2013-06-04T09:38:49.973 回答
3

尝试这个:

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;


}
于 2013-06-04T09:38:23.457 回答
1

您需要将该行private Label newLabel = new Label();放入for循环中。

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;
}
于 2013-06-04T09:38:01.020 回答