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,
};
Rien
  • 398
  • 2
  • 12
  • 37

1 Answers1

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.

keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • When trying your first option I get `Invalid initializer member declarator' and i dont exactly know how to use your alternative option. – Rien Apr 05 '15 at 14:52
  • You need to put it after the code you have, not inside the object initalizer. – keyboardP Apr 05 '15 at 14:59
  • Alright that works thanks! Why cant it be in the object initializer? And could explain the alternative method? I dont understand how to implement. – Rien Apr 05 '15 at 15:04
  • 1
    I don't know why there isn't syntactic sugar to allow events in the object initializer (see http://stackoverflow.com/questions/3993601/assigning-events-in-object-initializer). 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 https://msdn.microsoft.com/en-us/library/ms366768.aspx – keyboardP Apr 05 '15 at 15:20