Reputation: 32767
I have a table which keeps growing its size as the user inputs them, and each row has a 'X' Label to remove them as well.
table.RowCount is always up-to-date and so I have a function ~like following that is executed everytime I create a new row:
private void storeValues(){
Label removeLabel = new Label();
removeLabel.Text = "✗";
removLabel.Click += new EventHandler((s, e) => removeLabel_Click(s, e, table.RowCount));
}
The thing is that all removeLabel's always call the click event with the same parameter value which is the table.RowCount NOT the one I created them with but the value is currently having, so I'm always getting the last row deleted.
private void removeLabel_Click(object sender, EventArgs e, int index){
removeFromTable(index);
}
How can I save a fixed value to each removeLabel?
Upvotes: 0
Views: 114
Reputation: 1062855
Yes; that is what happens with lexical closures. The only thing you are actually capturing here is the implicit this
- the value of the expression this.table.RowCount
is evaluated at the time the delegate is invoked, every time the delegate is invoked.
If you want to capture a snapshot: capture a snapshot
var count = table.RowCount;
removLabel.Click += new EventHandler((s, e) => removeLabel_Click(s, e, count));
Upvotes: 2
Reputation: 22001
removeLabel.Tag = table.RowCount;
then get the Tag value in the event handler
Upvotes: 0