T.Todua
T.Todua

Reputation: 56557

How to combine events into 1 method?

by default, we add events in this way:

item1.Click += Click1;
item2.Click += Click2;

.....
private void Click1(){
    .....
}
private void  Click2(){
}

however, is there a way to combine it into one method, like:

item1.Click += Click(1);
item2.Click += Click(2);
....
private void Click(int num){
  if(num==1){
     ....
  }
  else if(num==2){
     ....
  }
}

(btw, newbie in C#)

Upvotes: 0

Views: 776

Answers (3)

Slai
Slai

Reputation: 22886

You can also compare the sender by reference:

item1.Click += Click;
item2.Click += Click;
....
void Click(object sender, EventArgs e)
{
    Control c = sender as Control;     // c = null if sender is not Control

    if (sender == item1)
        Debug.Print(c.Name + ", " + c.Text + ", " + c.Tag);
    else if (sender == item2)
        Debug.Print(c.Name + ", " + c.Text + ", " + c.Tag);
}

Upvotes: 1

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131722

That's how events always worked. You can use the same event handler for multiple events as long as the signature is the same. The base EventHandler type accepts a sender which is the object that fires the event and an EventArgs-derived parameter which is probided when the code fires the event.

For example, you can have a single click handler for multiple buttons :

void myHandler(object sender,EventArgs e)
{
    var theButton=(Button)sender;
    .....
}

button1.Click+=myHandler;
button2.Click+=myHandler;
button3.Click+=myHandler;
button4.Click+=myHandler;

Imagine you wanted to create a calculator with 10 digits. You could read the Text or Tag property of the sender to retrieve the digit :

void myDigitsHandler(object sender,EventArgs e)
{
    var theButton=(Button)sender;
    //You could store a number to the tag
    int digitFromTag=(int)theButton.Tag;

    //Or you could parse the text
    int digitFromText=int.Parse(theButton.Text);
    .....
}

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250326

Event handlers have sender argument usually which can be used to identify the actual sender:

void Click(object sender, EventArgs e)
{
    var btn= (Button)sender; // you can access properties which you might have set to identify which button it is 
    .....
}

button1.Click+=Click;
button2.Click+=Click;
button3.Click+=Click;
button4.Click+=Click;

It this is not sufficient and you want to pass some extra data to the handler, you could use a lambda :

void Click(object sender, EventArgs e, int extraInfo)
{
    var btn= (Button)sender;
    .....
}

button1.Click+=(s, e) => Click(s, e, 1);
button2.Click+=(s, e) => Click(s, e, 2);
button3.Click+=(s, e) => Click(s, e, 3);
button4.Click+=(s, e) => Click(s, e, 4);

Unsubscribing will be an issue with anonymous methods but if the handler owner and the control have the same lifespan inside a page then it might not matter as they will get GC-ed together anyway

Upvotes: 2

Related Questions