Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing extra parameters to the EventHandler

Hi I am trying to iterate over a list of custom buttons which I have created. It makes a call to a WCF Service to get some info from the DB.

foreach (LevelButton l in ls)
{
    WayFinderDBService.WayFinderDBServiceClient client = new    SilverlightNav.WayFinderDBService.WayFinderDBServiceClient();
    client.GetLevelDescriptionCompleted += new    EventHandler<SilverlightNav.WayFinderDBService.GetLevelDescriptionCompletedEventArgs>(client_GetLevelDescriptionCompleted);
    client.GetLevelDescriptionAsync(l.Name);                    
}

I am wanting to take whatever is returned from client.GetLevelDescriptionAsync(l.Name); and then pass this to the button e.g. l.Text = result;

My problem is passing a reference to the button as an extra parameter to the EventHandler. What is the right way to achieve what I want to do?

Thanks

like image 693
Marklar Avatar asked Feb 27 '26 05:02

Marklar


1 Answers

There are two approaches you might consider:

  • declare your own delegate type / event-args type with the extra data
  • have a public property on the raising class which exposes this data

if GetLevelDescriptionCompletedEventArgs is your type, then you're already doing the first - so just expose this value in the event-args type; you can consume it in an anonymous method:

foreach (LevelButton l in ls)
{
    LevelButton tmp = l;
    var client=new SilverlightNav.WayFinderDBService.WayFinderDBServiceClient();
    client.GetLevelDescriptionCompleted += delegate (object sender, GetLevelDescriptionCompletedEventArgs args) {
       tmp.Text = args.SomeProperty; // **must** be tmp.Text, not l.Text
    }
    client.GetLevelDescriptionAsync(tmp.Name); // or l.Name; same here
}

There is a problem, though - note the tmp above; this is the notorious foreach/capture issue.

like image 189
Marc Gravell Avatar answered Feb 28 '26 19:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!