C# 在C中动态添加循环下的控件#

C# 在C中动态添加循环下的控件#,c#,.net,winforms,linq,C#,.net,Winforms,Linq,我正在开发一个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(txtB

我正在开发一个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;


}
private Label newLabel=newLabel();
专用int txtBoxStartPosition=100;
专用int txtBoxStartPositionV=25;
对于(int i=0;i<7;i++)
{
newLabel.Location=新系统.Drawing.Point(txtBoxStartPosition,txtBoxStartPositionV);
newLabel.Size=新系统图纸尺寸(70,40);
newLabel.Text=i.ToString();
面板1.控件。添加(新标签);
txtBoxStartPositionV+=30;
}

这段代码只生成一个标签和文本7,但我想创建8个标签和他们各自的文本,我如何才能做到这一点

您需要放置行
私有标签newLabel=newLabel()for
循环中的code>

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;
}
private int txtBoxStartPosition=100;
专用int txtBoxStartPositionV=25;
对于(int i=0;i<7;i++)
{
Label newLabel=新标签();
newLabel.Location=新系统.Drawing.Point(txtBoxStartPosition,txtBoxStartPositionV);
newLabel.Size=新系统图纸尺寸(70,40);
newLabel.Text=i.ToString();
面板1.控件。添加(新标签);
txtBoxStartPositionV+=30;
}
试试这个:

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;


}
private int txtBoxStartPosition=100;
专用int txtBoxStartPositionV=25;
对于(int i=0;i<7;i++)
{
newLabel=新标签();
newLabel.Location=新系统.Drawing.Point(txtBoxStartPosition,txtBoxStartPositionV);
newLabel.Size=新系统图纸尺寸(70,40);
newLabel.Text=i.ToString();
面板1.控件。添加(新标签);
txtBoxStartPositionV+=30;
}

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

private Label newLabel;

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

按照示例从行中删除
private
。您一开始并没有这么说;)
for (int i = 0; i < 8; i++)