-1

How can we provide single generic method for collection of command buttons. I have collection of digit(0, 1,2..) command buttons and need to have single event method for all of them as they have similar behavior.

pbd
  • 423
  • 3
  • 8
  • 19

2 Answers2

2

The pattern for delegates for events is use two parameters. One is the sender, the other is the eventargs. You can do something based on the sender or you can put some stuff in the tag

void OnButtonClick(object sender, EventArgs e)
        {
            Button button = sender as Button;

            object data = button.Tag;
            DoSomething(data);
        }
AbdElRaheim
  • 1,384
  • 6
  • 8
1

You can achieve this by Multicast Delegates

  1. Define GenericButtonClick event handler this way:

    void OnGenenicButtonClick(object sender, EventArgs e)
    {
        var btn = sender as Button;
        // ... do something ...
    }
    
  2. Assign the GenericButtonClick event delegate this way (in say Load event handler):

    cmdBtn1.Click += OnGenenicButtonClick;
    cmdBtn2.Click += OnGenenicButtonClick;
    //...
    

Reference:

Community
  • 1
  • 1
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93