简体   繁体   中英

C# pass additional parameter to an event handler while binding the event at the run time

I have a link button which have a regular click event :

protected void lnkSynEvent_Click(object sender, EventArgs e)
{
}

And I bind this event at the runtime :

lnkSynEvent.Click += new EventHandler(lnkSynEvent_Click);

Now I need the function to accept additional argument:

protected void lnkSynEvent_Click(object sender, EventArgs e, DataTable dataT)
{
}

And pass the same as parameter while binding this event :

lnkSynEvent.Click += new EventHandler(lnkSynEvent_Click, //somehow here);

Not sure how to achieve this. Please help.

Thanks in advance.

Vishal

You can use anonymous delegate for that:

lnkSynEvent.Click += 
         new EventHandler((s,e)=>lnkSynEvent_Click(s, e, your_parameter));

我不确切知道它什么时候改变了,但现在它更容易了!

lnkSynEvent.Click += (s,e) => lnkSynEvent_Click(s, e, your_parameter);

by use of delegate:

lnkbtnDel.Click += delegate(object s, EventArgs e1) { 
                 Dynamic_Click(s, e1, lnkbtnDel.ID); 
               };`  
EventHandler myEvent = (sender, e) => MyMethod(myParameter);//my delegate

myButton.Click += myEvent;//suscribe
myButton.Click -= myEvent;//unsuscribe

private void MyMethod(MyParameterType myParameter)
{
 //Do something
}

All answers above seem to be fine, but I have discovered one pitfall which is not so obvious and it took some time to figure out what is going on, so I wanted to share it.

Assume that myList.Count returns 16.

In the following case, OnValueChangeWithIndex(p1, p2, i) will always be called with i = 16 .

for (int i = 0; i < myList.Count; i++)
{
    myList[i].OnValueChange += (p1, p2) => OnValueChangeWithIndex(p1, p2, i);
}

To avoid that, you would need to initialize a new variable inside of the loop, then pass the new variable to the function.

for (int i = 0; i < myList.Count; i++)
{
    int index = i;
    myList[i].OnValueChange += (p1, p2) => OnValueChangeWithIndex(p1, p2, index);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM