0

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.

2
  • Does this work? If not, what happens? Commented Sep 23, 2014 at 17:38
  • As I said. It always redirect me to Showroom.aspx with STT = 4 (which is i after the loop) Commented Sep 23, 2014 at 17:45

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to copy i to a local variable. Or as the other Answer suggests, build your URL before its used in your lambda expression.

            int x = i;
            image.Click += (s, args) =>
            {
                Response.Redirect("~/Showroom.aspx?STT=" + (x));
            };

1 Comment

Yeah! It works. I didn't think of storing it as a local variable :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.