0

I'm new to C# and messing around with event Handlers. I have lots of panels in my form. I want them to change colors if my Mouse ist over them. I can create individual functions in my Form.cs for every panel. Is there a more efficient way? Can you pass a parameter with the event and do something like this and send a the needed Panel as a Parameter?
private void Panel_MouseEnter(object sender, EventArgs e, Panel p)
    {
        p.BackColor=System.Draw.etc;
    }

How would i have to call it from my Form.Designer.cs?

MrSmoer
  • 44
  • 5

2 Answers2

2

The panel is actually the sender, all you need is Panel p = (Panel)sender;
Because of this, the event can actually be re-used for all of the panels.

This means that you can register all of your panels hover event to the same function.

The full code:

private void Panel_MouseEnter(object sender, EventArgs e)
{
    Panel p = (Panel)sender;
    p.BackColor=System.Draw.etc;
}
TheSiIence
  • 327
  • 2
  • 10
0

You can write:

private void Panel_MouseEnter(object sender, EventArgs e)
{
  var panel = sender as Panel;
  if ( panel != null ) 
    panel.BackColor = Color.White;
}

The sender parameter is the control which raises the event.

The as typecasting operator returns null if the instance is of wrong type.

So we check if not null and set the color.

Then all you need is to manually assign this handler to the event of each panel or any control you want.

Or you can automate that for example by putting all desired controls in a panel and writting somewhere, in the form load event handler for example:

// Set for all panels in this panel but not recursively
MyContainerPanel.Controls.OfType<Panel>()
                         .ToList()
                         .ForEach(c => c.MouseEnter += Panel_MouseEnter);

// Set for all panels in the form but not recursively
Controls.OfType<Panel>()
        .ToList()
        .ForEach(c => c.MouseEnter += Panel_MouseEnter);

Also you can filter on the name, a property even the tag:

Controls.OfType<Panel>()
        .Where(c => c.Name.StartsWith("panelColorizable"))
        .ToList()
        .ForEach(c => c.MouseEnter += Panel_MouseEnter);

To assign recursively you can take a look at:

How to toggle visibility in Windows Forms C#

How to format all textbox values on LostFocus event in Winform

Also you can do the same thing on the mouse leav.