Search code examples
c#asp.netwindowslabel

Can we create multiple events during runtime in C# for controls which are created during runtime


Here I am creating few controls during run time with help of following code which is working fine and good.But along with that I have to perform certain tasks on events of these controls which are generated during run time

 private void btnExtra_Click(object sender, EventArgs e)
            {
                AddNewLabel();
            }

            int count = 1;
            public System.Windows.Forms.Label AddNewLabel()
            {
                System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
                lbl.Name = "LabelX" + this.count.ToString();
                lbl.ForeColor = Color.Black;
                lbl.Font = new Font("Sego UI", 8, FontStyle.Bold);
                lbl.Top = count * 25;
                lbl.Left = 100;
                lbl.Text = "Label 1 " + this.count.ToString();
                lbl.BringToFront();
                panel4.Controls.Add(lbl);
                count = count + 1;
                return lbl;
            }

Solution

  • can you try this

    public System.Windows.Forms.Label AddNewLabel()
    {
        System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
        lbl.Name = "LabelX" + this.count.ToString();
        lbl.ForeColor = Color.Black;
        lbl.Font = new Font("Sego UI", 8, FontStyle.Bold);
        lbl.Top = count * 25;
        lbl.Left = 100;
        lbl.Text = "Label 1 " + this.count.ToString();
        lbl.DoubleClick += Lbl_DoubleClick;
        lbl.BringToFront();
        panel4.Controls.Add(lbl);
        count = count + 1;
        return lbl;
    }
    private void Lbl_DoubleClick(object sender, EventArgs e)
    {
        ((Label)sender).Text = "Double Click";
    }