2

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");
}
6
  • 1
    No. That's fine. They can be contained inside other controls. Commented Nov 21, 2013 at 21:36
  • so how do i get this to work, because everything looks fine, but it doesn't trigger the event.. Commented Nov 21, 2013 at 21:38
  • Are you clicking on the panel itself or the label inside the panel? Commented Nov 21, 2013 at 21:38
  • you added the event only on item's mouseclick, you should be adding the mouseclick event handler even to the label Commented Nov 21, 2013 at 21:41
  • If you will add the following lines to your code you'll see how LarsTech's answer fixes your code: pnlItem.BackColor = Color.Blue; and: lbl.BackColor = Color.Red; And click on the blue area. Commented Nov 21, 2013 at 21:46

2 Answers 2

2

You are clicking on the label. Add that handler, too:

pnlItem.MouseClick += pnlItem_MouseClick;
lbl.MouseClick += pnlItem_MouseClick;
Sign up to request clarification or add additional context in comments.

Comments

0

Yeah, you're either clicking the label or no part of the panel at all. I tried the code, it works, but do what the others have said and add a back color so you know where to click. Be aware the areas around the label may also register as the "label" even though it seems as though you are clicking on the panel itself, (the area directly below it especially).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.