I’m trying to pass two values on Button_Click Event
public MyClass()
{
Int64 po = 123456;
foreach (Expense expense in pr.Expenses)
{
Button btnExpenseDetail = new Button();
btnExpenseDetail.Text = expense.ExpenseName;
btnExpenseDetail.Location = new Point(startLocation.X + 410, startLocation.Y + (23 *
btnExpenseDetail.Click += (sender, e) => { MyHandler(sender, e, po , expense.ExpenseName); };
pnlProjectSummary_Expenses.Controls.Add(btnExpenseDetail);
}
}
void MyHandler(object sender, EventArgs e, string po, string category)
{
FormExpenseDetails ed = new FormExpenseDetails(po, category);
ed.Show();
}
I’m using visual studio 2010 c#. On the panel each Button’s text values are all different. But the the buttons’ Click_Events are acting all the same. Could someone tell me which part of code i am getting this logical error?
========================================================================
Looks like a common pitfall with enumerators. Basically if you use the enumerator variable (
expensein this case) for a lambda, it always creates a closure over the same variable, so it always uses the same value. You can fix it like this:You can think of your lambda as being passed a reference to the variable
expense. Even though the value of the variable changes with each iteration, the reference still points to the same variable. That is why it helps creating a locally scoped variable for each iteration (currentExpense). The string value and also the location are different because they are assigned to another location (Button.Text,Button.Location) each iteration.