我尝试使用下面的代码动态添加面板及其事件处理程序。

但是,它与许多可用的答案类似,似乎不起作用(单击时触发事件)。

如果可以的话请帮忙。

int items = 0;

private void Form1_Load(object sender, EventArgs e)
{
    ArrayList al = new ArrayList();

    foreach (KnownColor knowColor in Enum.GetValues(typeof(KnownColor)))
    {
        Color color = Color.FromKnownColor(knowColor);
        al.Add(color.Name);
    }

    foreach (string i in al)
    {
        addListItem(i);
    }
}

public void addListItem(string item)
{
    Panel pnlItem = new Panel();

    pnlItem.Location = new Point(0, items * 25);
    pnlItem.Name = "pnl" + item;
    pnlItem.Size = new Size(250, 25);
    pnlList.Controls.Add(pnlItem);

    Label lbl = new Label();
    lbl.Text = item;
    pnlItem.Controls.Add(lbl);

    pnlItem.MouseClick += new MouseEventHandler(pnlItem_MouseClick);

    items++;
}

void pnlItem_MouseClick(object sender, MouseEventArgs e)
{
    MessageBox.Show("panel was clicked");
}

最佳答案

您正在单击标签。也添加该处理程序:

pnlItem.MouseClick += pnlItem_MouseClick;
lbl.MouseClick += pnlItem_MouseClick;

关于c# - 动态添加控件和事件处理程序C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20132231/

10-11 16:00