Androidizing Androidizing -4 years ago 71
ASP.NET (C#) Question

Dynamically create multiple ImageButton controls and wire-up Click event

I'm pretty new to ASP.NET. Please forgive me for my knowledge :) Assuming I want to create 4 imagebuttons. If I click on any imagebutton, it will move me to another page with different STT (<- just a name).
Here's my code:

for (int i= 0; i< 4; i++)
{
ImageButton image = new ImageButton();
image.Click += (s, args) =>
{
Response.Redirect("~/Showroom.aspx?STT=" + (i));
};
//other things to do
}


Now the problem is that when I click on any imagebutton. I'll be redirected to Showroom.aspx with STT = 4 (which is i after the loop). How can I be redirected to the page with desired STT.

EDIT:
Just to clarify. What I want is Clicking on imagebutton 1 will move me to Showroom.aspx with STT = 0. Imagebutton 2 will move me to the page with STT=1 and so on.

Answer Source

Problem

"~/Showroom.aspx?STT=" + (i) means it captures the variable i rather than its value at the time of delegates creation.

Solution

Create url outside of delegate.

for (int i = 0; i < 3; i++)
{
    string url = string.Format("~/Showroom.aspx?STT={0}", i);
    var image = new ImageButton();
    image.Click += (s, args) => Response.Redirect(url);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download