Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I am trying to add mutible eventhandlers for a array of TextBlocks, but it seems like it is always the last element of sHeadline[x] that gets the eventhandler. For example if I have 10 elements of sHeadline[x] it is always sHeadline[9] that gets the eventhandler.
How can I fix this?
Thanks!

C#
void service_GetSearchForVesselCompleted(object sender, PositionServiceReference.GetSearchForVesselCompletedEventArgs e)
{
  // Number of results
  var numberOfResults = e.Result.Count;

  // Variables
  String vesselName;
  SolidColorBrush textColor = new SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 30, 30, 30));

  // Create headlines
  TextBlock[] sHeadline = new TextBlock[numberOfResults];

  // Go trough results list
  for (int x = 0; x < numberOfResults; x++)
  {
    // Get vales
    vesselName = e.Result[x].Vessel_Name;

    sHeadline[x] = new TextBlock();
    sHeadline[x].TextDecorations = TextDecorations.Underline;
    sHeadline[x].FontSize = 12;
    sHeadline[x].Text = vesselName;
    sHeadline[x].Margin = new Thickness(9, 0, 0, 0);
    sHeadline[x].Height = 15;
    stackPanelSearchResults.Children.Add(sHeadline[x]);

    // Add listners
    sHeadline[x].MouseLeftButtonDown += new MouseButtonEventHandler((object senderH, MouseButtonEventArgs eH) => sHeadline_MouseLeftButtonDown(senderH, eH, vesselName, x));
  }
}

void sHeadline_MouseLeftButtonDown(object sender, MouseButtonEventArgs e, string inpVesselName, int x)
{
  labelStatus.Content = "Click on " + inpVesselName + " " + x;
}
Posted

1 solution

This sort of answers the same question:

http://stackoverflow.com/questions/4155691/c-sharp-lambda-local-variable-value-not-taken-when-you-think[^]

but basically you are not storing the value of vesselname and x when you create the lambda but the catual variable themselves so they get stuck on their last value for all of those handlers.
 
Share this answer
 
Comments
Solo1233211 21-Feb-13 12:30pm    
Yes, I understand, but how can i achieve this?
Chris Reynolds (UK) 21-Feb-13 12:36pm    
Dashing this off before I go home without testing, but you should be able to get the answer from the link. Basically, create variables in the loop
for (int x = 0; x < numberOfResults; x++)
{
// Get vales
string LoopvesselName = e.Result[x].Vessel_Name;
int loopx = x;
sHeadline[x].MouseLeftButtonDown += new MouseButtonEventHandler((object senderH, MouseButtonEventArgs eH) => sHeadline_MouseLeftButtonDown(senderH, eH, LoopvesselName, loopx));
}
Solo1233211 21-Feb-13 12:52pm    
Thank you! This is a very elegant solution!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900