Kushan Peiris
Kushan Peiris

Reputation: 167

Having dynamically created label on separate lines

The following method is used by me to create a set of dynamic widgets on a button click and display the contents of an array in the labels!

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);
    }
}

The problem I face is that some labels display on the same line but I want only one label in each line! How can I modify my code?

Upvotes: 1

Views: 336

Answers (3)

Avinash Shingole
Avinash Shingole

Reputation: 76

You can use this. This is simple...

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;
    }
}

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39946

You should use flowLayoutPanel1.SetFlowBreak(lbl, true); like this:

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);
}

However currently you are creating the label in each iteration of the loop. If you just need one label with line breaks you can change your code like below:

Label lbl = new Label();

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

Upvotes: 2

Znaneswar
Znaneswar

Reputation: 3387

Try this

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;
 }

Upvotes: 0

Related Questions