matteo0402
matteo0402

Reputation: 7

Unique dynamic panel - differentiate between dynamically generated panels - C#

so I'm creating some dynamic panels to a flowLayoutPanel, and want to display their name on a label, when hovering, but it always give me the latest created panel name.

My code:

private void create_Click(object sender, EventArgs e)
    {
        Panel p = new Panel();
        p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
        p.BackColor = Color.FromArgb(123, R.Next(222), R.Next(222));
        p.Size = new Size(flowLayoutPanel1.ClientSize.Width, 50);
        p.MouseEnter += new System.EventHandler(this.p_MouseEnter);
        p.MouseLeave += new System.EventHandler(this.p_MouseLeave);
        flowLayoutPanel1.Controls.Add(p);
        flowLayoutPanel1.Controls.SetChildIndex(p, 0);

        

        p.Paint += (ss, ee) => { ee.Graphics.DrawString(p.Name, Font, Brushes.White, 22, 11); };
        flowLayoutPanel1.Invalidate();

        ID = p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
    }

private void p_MouseEnter(object sender, EventArgs e)
    {
        label1.Text = ID.ToString();
    }

Any idea on how to fix this, will be much appreciated!

Upvotes: 0

Views: 61

Answers (1)

Enigmativity
Enigmativity

Reputation: 117124

Just after the p.Paint line you should do this:

    p.MouseEnter += (ss, ee) => label1.Text = p.Name;

Upvotes: 1

Related Questions