I want to Run following clicking Event inside the for loop.. When i=0
in for loop, following event i=3
I have no idea why it is not equal to 0
. This is the Event I used..
MessageBox.Show(i.ToString()); // i= 3
string strUrl = linkbuilder[i];
Process proc = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(strUrl);
proc.StartInfo = startInfo;
proc.Start();
};
Here is the whole code i tried
{
string[] idlist = textBox1.Text.Split('\n');
// string[] title = textBox2.Text.Split('\n');
string[] shippingcost = textBox3.Text.Split('\n');
string[] newuserbonus = textBox4.Text.Split('\n');
// string[] itemprice = textBox5.Text.Split('\n');
string[] linkbuilder = textBox6.Text.Split('\n');
for (int i = 0; i < idlist.Length - 1; i )
{
LinkLabel ln = new LinkLabel();
string A = null;
ListViewItem items = new ListViewItem((i 1).ToString());
// items.SubItems.Add(title[i]);
items.SubItems.Add(shippingcost[i]);
items.SubItems.Add(newuserbonus[i]);
// items.SubItems.Add(itemprice[i]);
// items.SubItems.Add("views");
// this.listView1.Controls.Add(btn);
listView1.Items.Add(items);
ln.Text = "View";
//btn.BackColor = SystemColors.ButtonFace;
Point p = this.listView1.Items[i].Position;
p.X = 1000;
ln.Location = p;
ln.Click = (object senderw, EventArgs ew) => {
string strUrl = linkbuilder[i]; // <============= i =3 WHY?? WHY?? WHY IT IS NOT 0
Process proc = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo(strUrl);
proc.StartInfo = startInfo;
proc.Start();
};
this.listView1.Controls.Add(ln);
}
timer1.Stop();
}
Please help me. I want to set to i = 0
in the clicking Event(ln.Click()
). But it is equal to 3
. Please show me my fault. Thanks
CodePudding user response:
Your issue is with how anonymous function capture variables in scope. When you create an anonymous function, the captured variables from the enclosing scope are not copied, as they would be were they function parameters. Instead, the anonymous function looks up the variable from the enclosing scope, which is retained even if it would normally pass out of scope. The upshot of this is that your click handler will always use the value of i at the time of click not at the time of closure declaration. Remember closures capture variables not values.
The simplest solution is to not use a for loop, but instead use a Linq function or the ForEach
method on a list. That ensures that each iteration captures a different scope.
Additionally, you have an antipattern here called the parallel collection antipattern. You have a bunch of collections that you assume have the same length. These should be one collection with a complex object, so you aren't constantly indexing. Use a single list with a complex model object and a .ForEach and this should work just fine.