Click here to Skip to main content
15,886,823 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm creating a simple gallery for my photos. I'm quite new to asp.net.
Whenever I click on the next photo button, the counter loses value on the postback and remains on the same image.
How can I make a counter that doesn't lose value? Or is there any other way I can do this at all?
Please explain in simple English, remember I'm new to this. thanks.


C#
int counter = 0;
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
       {
           counter++;
           ImageGallery.ImageUrl = "~/Images/" + counter.ToString() + ".jpg";
Posted

1 solution

Web application cannot maintain state like Windows application. Any class member defined will be reconstructed during the page request(or sometimes called roundtrip or postback etc) processing. But there are bunch of alternative ways that you can maintain state of a varible.But I list here couple of ways to save the variable for the next request.
1)Store in Session. ex:
inside the ImageButton2_click,
if(Session["counter"]!=null)
{
counter = Convert.ToInt32(Session["counter"]);
}

Session["counter"] = ++counter
2)HiddenField element, read/store like it is done in Session example.

To learn more about ASP.NET/Web Applications, I suggest practice Visual Studio installed samples besides reading the books.
 
Share this answer
 
Comments
LighthouseCall 21-Jan-12 18:40pm    
Works wonders! Thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900