J
james
Hi guys,
I create a delegate and pass in a local variable. When the variable
is a reference type everything works fine, but when it is a valuetype
the delegate uses the value of the last instance that was created
(sorry that was a mouthful). Heres an example of the problem:
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, (int)(i/2), i%2);
++i;
}
}
When I ran that, no matter which button was pressed, m_selectedUrl
equaled the value of the last DictionaryEntry in bookmarks. Any
ideas?
Thanks,
James
I create a delegate and pass in a local variable. When the variable
is a reference type everything works fine, but when it is a valuetype
the delegate uses the value of the last instance that was created
(sorry that was a mouthful). Heres an example of the problem:
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, (int)(i/2), i%2);
++i;
}
}
When I ran that, no matter which button was pressed, m_selectedUrl
equaled the value of the last DictionaryEntry in bookmarks. Any
ideas?
Thanks,
James