Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call an eventhandler with arguments

Visual Studio 2008, C# 3.0.

I have a method below which calls an event handler. I would like to pass the two arguments received by the method to the event handler.

I would like to do something like this:

wc.DownloadDataCompleted += wc.DownloadedDataCompleted(strtitle, placeid);

Is this even possible, if yes, how would I go about doing it ?

Code Snippet:

public void downloadphoto(string struri,string strtitle,string placeid)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadDataCompleted += wc_DownloadDataCompleted;
        wc.DownloadDataAsync(new Uri(struri));
    }
}
like image 766
dezkev Avatar asked Sep 28 '09 16:09

dezkev


People also ask

How do you pass arguments to an event handler?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

What is the difference between an event and an EventHandler?

In programming, an event handler is a callback routine that operates asynchronously once an event takes place. It dictates the action that follows the event. The programmer writes a code for this action to take place. An event is an action that takes place when a user interacts with a program.

Is an EventHandler a delegate?

The EventHandler delegate is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must use the generic EventHandler<TEventArgs> delegate class.

When would you use an event handler?

Use the EventHandler delegate for all events that don't include event data. Use the EventHandler<TEventArgs> delegate for events that include data about the event. These delegates have no return type value and take two parameters (an object for the source of the event and an object for event data).


1 Answers

The easiest way to do this is to use an anonymous function (an anonymous method or a lambda expression) to subscribe to the event, then make your method have just the parameters you want:

public void downloadphoto(string struri, string strtitle, string placeid)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadDataCompleted += (sender, args) => 
            DownloadDataCompleted(strtitle, placeid, args);
        wc.DownloadDataAsync(new Uri(struri));
    }
}

// Please rename the method to say what it does rather than where it's used :)
private void DownloadDataCompleted(string title, string id, 
                                   DownloadDataCompletedEventArgs args)
{
    // Do stuff here
}
like image 167
Jon Skeet Avatar answered Oct 20 '22 11:10

Jon Skeet