views:

283

answers:

1

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

+1  A: 

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.

Marc Gravell
Cheers for that mate thats exactly what I was after
Tim