Search code examples
c#winformseventscode-duplication

Compact way of assigning same handler to many events


In my user control code I noticed lots of events with the same handler:

btnMas.MouseDown += MyMouseDown;
btnMenos.MouseDown += MyMouseDown;
txtValue.MouseDown += MyMouseDown;
lblMax.MouseDown += MyMouseDown;
lblMin.MouseDown += MyMouseDown;
lblName.MouseDown += MyMouseDown;

Is there a more compact way to write this? As in iterating over a collection of events, or using lambdas?


Solution

  • If you're subscribing to the same event on many objects, and that event is exposed by some base class, you could use:

    var controls = new Control[] { btnMas, btnMenos, txtValue,
                                   lblMax, lblMin, lblName };
    foreach (var control in controls)
    {
        control.MouseDown += MyMouseDown;
    }
    

    I'm not sure that's really any cleaner, mind you. Of course it becomes a lot cleaner if you need to do several different operations to the same set of controls.

    EDIT: Given the extra information, it's really as simple as:

    foreach (Control control in this.Controls)
    {
        control.MouseDown += MyMouseDown;
    }