hi,

i would like to create components at runtime. i've added a label to the form and set its properties at design time. now i want to create 8 more copies of the label when the program starts (oc with the same properties).

how can i add them and refer to them?

TIA,
Sean

Recommended Answers

All 3 Replies

Did you try to search this site?
I think it contains already all you need to know:)
I searched for add labels at runtime The first thread I found was : http://www.daniweb.com/forums/thread200667.html
If you can't figure it out, please come back here with your questions.

thanks ddanbe, i searched and read that thread before posting. it helped me too much but my question is slightly different.

i've added a label to my form at design time and set its properties to fit my needs. i even assigned a handler for the click event. now i would like to create 8 more copies of it with the same properties and same event handler.

to be more specific, i have a label called lblCell1 and now i want to have lblCell2, lblCell3, ..., lblCell9. something like cloning the lblCell1 label at runtime.

Unless you understand the difference between a shallow and a deep copy of an object very well, I should say :
What is wrong with the following?
I copied the code from the thread and adapted it a little bit.
Remove your design label and do all your labels at runtime like this:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            for (int i = 1; i <= 9; i++) //add 9 labels and their properties
            {
                Label newlabel = new Label();
                newlabel.AutoSize = true;
                newlabel.Text = i.ToString();
                newlabel.Location = new System.Drawing.Point(50, 20 + 30 * i);
                newlabel.Name = "lblCell" + i.ToString();
                newlabel.Size = new System.Drawing.Size(60, 25);
                newlabel.BorderStyle = BorderStyle.FixedSingle;
                //more properties here if you want
                this.Controls.Add(newlabel);
            }
        }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.