Reputation: 113
I have this code to create a new label with a variable attached to it but I get an error (obviously). Is there a way to do this?
System.Windows.Forms.Label lbl_Task[i] = new System.Windows.Forms.Label();
I.e, if i == 4, the label would be called lbl_Task4. If i == 9, it would be lbl_Task9, etc.
Edit:
New code shows:
for (int i = 0; i < rows; i++)
{
//create a label for the Task Name
Label lbl = new Label();
lbl.Name = "lbl_Task" + i;
tableLayoutPanel1.SetColumnSpan(lbl, 4);
lbl.Dock = System.Windows.Forms.DockStyle.Fill;
lbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
lbl.Location = new System.Drawing.Point(3, pointInt);
lbl.Size = new System.Drawing.Size(170, 24);
lbl.TabIndex = 8;
lbl.Text = Convert.ToString(dtTasks.Rows[i]["Task_Name"]);
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Controls.Add(lbl);
pointInt += 24;
}
This compiles but does not show on my win form when I debug. Any ideas?
Upvotes: 0
Views: 4255
Reputation: 1639
Use a collection of Lables and try like this
List<Label> labels = new List<Label>();
for (int i = 0; i < 100; i++)
{
Label label = new Label();
// Set Lable properties
yourLayoutName.Controls.Add(label);//add the lable
labels.Add(label);
}
Upvotes: 0
Reputation: 101731
You are looking for something like this:
for(int i =0; i<10; i++)
{
Label lbl = new Label();
lbl.Name = "lbl_Task" + i;
// set other properties
this.Controls.Add(lbl);
}
Upvotes: 1