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.
Asked
Active
Viewed 1,274 times
-1
-
pls show your tried code – cuongle Oct 31 '12 at 02:50
-
do you mean invoking each button with one single method?? like commandButtons1.Click += new EventHandler(object sender, EventArgs e) – Selalu_Ingin_Belajar Oct 31 '12 at 03:06
2 Answers
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
Define
GenericButtonClick
event handler this way:void OnGenenicButtonClick(object sender, EventArgs e) { var btn = sender as Button; // ... do something ... }
Assign the
GenericButtonClick
event delegate this way (in sayLoad
event handler):cmdBtn1.Click += OnGenenicButtonClick; cmdBtn2.Click += OnGenenicButtonClick; //...
Reference:
- You can also have a look at the difference of Simple Delegate (delegate) vs. Multicast delegates

Community
- 1
- 1

Furqan Safdar
- 16,260
- 13
- 59
- 93