简体   繁体   中英

Creating a win form label in c# code using variable?

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

Ie, 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM