I have tried to dynamically add panels and their event handlers using the code below.
However it does not seem to work (trigger the event when clicked) although it is similar to many of the available answers.
Please help if possible.
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.BackColor = Color.Blue;and:lbl.BackColor = Color.Red;And click on the blue area.