0

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?

5
  • instead of relying on Label's name, use Control.Tag property to store i, The way you are creating label is wrong. Should be like: System.Windows.Forms.Label lbl_Task = new System.Windows.Forms.Label(); lbl_Task.Tag = i; Commented Mar 21, 2014 at 19:47
  • 1
    Don't write code like this, it performs very poorly beyond getting it wrong. Use a ListBox or ListView instead. Commented Mar 21, 2014 at 20:16
  • You are going to have to document what you are doing with that TableLayoutPanel control and how the Label controls relate to it. Commented Mar 21, 2014 at 20:18
  • What @HansPassant says, or GDI+ it. Commented Mar 21, 2014 at 20:29
  • Normally I wouldn't write code like this, however it was an experiment to see if it could be done this way! Commented Jul 7, 2014 at 18:55

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.