0

I have a loop that could create 1 or maybe 10 or maybe 584575 (example, not actually true) FlowLayoutPanels. For all these panels I want a hover event handler, or maybe later another type of event handler but for now only hover.

How can I make this happen for multiple same type created controls?

FlowLayoutPanel finalResult_panel = new FlowLayoutPanel{
       FlowDirection = FlowDirection.LeftToRight,
       BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle,
       Name = "result_flowLayoutPanel" + i,
       Size = new System.Drawing.Size(790, 72),
       TabIndex = i,
};

1 Answer 1

1

You can attach the handler like this

finalResult_panel.MouseHover += panel_MouseHover;

private void panel_MouseHover(object sender, EventArgs e) 
{

}

Alternatively you can create an anonymous delegate

finalResult_panel_MouseHover += (s,e) => {
                                            //event code 
                                         };

These will attach the same handlers to every panel so if you need to differentiate, you can do that in the handler itself (using the sender property) or somehow differentiate before attaching the handler.

Sign up to request clarification or add additional context in comments.

4 Comments

When trying your first option I get `Invalid initializer member declarator' and i dont exactly know how to use your alternative option.
You need to put it after the code you have, not inside the object initalizer.
Alright that works thanks! Why cant it be in the object initializer? And could explain the alternative method? I dont understand how to implement.
I don't know why there isn't syntactic sugar to allow events in the object initializer (see stackoverflow.com/questions/3993601/…). The second method is an anonymous function that uses a lambda expression. Where I've put event code is where the code goes for the handler. There's more information here msdn.microsoft.com/en-us/library/ms366768.aspx

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.