独特的动态面板 - 区分动态生成的面板 - C#

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

所以我正在为 flowLayoutPanel 创建一些动态面板,并希望在悬停时在标签上显示它们的名称,但它总是给我最新创建的面板名称。

我的代码:

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

任何关于如何解决这个问题的想法,将不胜感激!

p.Paint 行之后你应该这样做:

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