在单独的行上动态创建标签

Having dynamically created label on separate lines

我使用以下方法在单击按钮时创建一组动态小部件,并在标签中显示数组的内容!

public void addLabel()
{
    for (int i = 0; i < array.Length; i++)
    {
        Label lbl = new Label();
        lbl.Text = array[i]+"\n";
        lbl.AutoSize = true;
        flowLayoutPanel1.Controls.Add(lbl);
    }
}

我遇到的问题是有些标签显示在同一行,但我只想在每一行显示一个标签!如何修改我的代码?

你应该这样使用flowLayoutPanel1.SetFlowBreak(lbl, true);

for (int i = 0; i < array.Length; i++)
{
    Label lbl = new Label();
    lbl.Text += array[i] + "\n";
    lbl.AutoSize = true;
    flowLayoutPanel1.Controls.Add(lbl);
    flowLayoutPanel1.SetFlowBreak(lbl, true);
}

但是目前您正在循环的每次迭代中创建 label。如果您只需要一个带有换行符的标签,您可以像下面这样更改您的代码:

Label lbl = new Label();

for (int i = 0; i < array.Length; i++)
{
    lbl.Text += array[i] + "\n";  
}
lbl.AutoSize = true;
flowLayoutPanel1.Controls.Add(lbl);

试试这个

int lblStartPosition = 100;
int lblStartPositionV = 25;

for (int i = 0; i < array.Length; i++)
 {
       Label lbl = new Label();
       lbl.Text = array[i]+"\n";
       lbl.AutoSize = true;
       lbl.Location = new System.Drawing.Point(lblStartPosition , lblStartPositionV);
       flowLayoutPanel1.Controls.Add(lbl);
       lblstartPositionV += 30;
 }

你可以用这个。这很简单...

public void addLabel()
{          
    for (int i = 0; i < array.Length; i++)
    {
        Label lbl = new Label();
        lbl.Text = array[i] + "\n";
        lbl.AutoSize = true;
        flowLayoutPanel1.Controls.Add(lbl);
        flowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
    }
}