(Sorry if this is a double post)
Hi Guys,
I am creating a delegate a couple times and passing in a local
variable. However, when the delegate is invoked it uses the variable
passed into the last created instance (sorry that was a mouthful).
Here is an example from my code:
private void dlgFavorites_Load(object sender, EventArgs e)
{
Hashtable bookmarks =
ConfigurationSettings.GetConfig("Bookmarks") as Hashtable;
if(bookmarks == null)
return;
int i = 0;
foreach (DictionaryEntry pair in bookmarks)
{
Button btn = new Button();
btn.DialogResult = DialogResult.OK;
btn.Text = (string)pair.Key;
btn.Click += new EventHandler(delegate
{
m_selectedUrl = (string)pair.Value;
});
btn.Dock = DockStyle.Fill;
tableLayoutPanel1.Controls.Add(btn, i%2, (int)(i/2));
++i;
}
}
I was able to get around the problem by doing:
string value = (string)pair.Value;
btn.Click += new EventHandler(delegate
{
m_selectedUrl = value;
});
So I think it has something to do with boxing ValueTypes. Anyway I
would love to hear any ideas.
Thanks,
James