9

I don't know alot about ASP.Net but I'm trying to make a new control for a message box. You enter some info and press a button.

However, for some bizarre reason when the button is pressed, Page_Load() gets called a second time, and all of the member variables are reset to null! I need those variables, and Page_Load() has not reason to be called a second time! Of course the callstack is useless.

evilfred
  • 2,314
  • 4
  • 29
  • 44

10 Answers10

19

Remember, in ASP.Net every time you cause a postback of any kind, including handling events like button clicks, you're working with a brand new instance of your page class that must be rebuilt from scratch. Any work you've done previously to build the page on the server is gone. That means running the entire page life cycle, including your page load code, and not just the click code.

Always two there are, no more, no less. A request and a response.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 1
    guhhh so instance variables are useless? this is weird because I did the exact same stuff elsewhere in the webpage and they work fine, i didn't happen to hit re-instantation there somehow i guess. – evilfred Jul 07 '09 at 21:27
  • 1
    Instance variables are useful for holding data in between events in the same postback. For example, you could open an sql connection early and use that same connection later in the life cycle. Where instance variables work elsewhere across postbacks you're likely relying on ViewState. – Joel Coehoorn Jul 07 '09 at 21:30
  • +1 for thinking about the *most obvious* thing first rather than going through more advanced speculations! – Mehrdad Afshari Jul 07 '09 at 21:32
  • 6
    +1 for not only being the right answer, but throwing in an appropriate Star Wars reference. – Adrien Jul 07 '09 at 21:33
  • Another way to remember this is that instance variables represent the "state" of your page class (or any class), and the web is stateless. – Joel Coehoorn Jul 07 '09 at 21:33
  • You can use instance variables as long as it's during a single Request. Once the page is served to the user and they click a button, that's a second request with its own instance variables. State management in ASP.net is a whole can of worms, but you need to deal with it to do anything. http://www.exforsys.com/tutorials/asp.net/managing-state-with-asp.net-and-csharp.html – Greg Jul 07 '09 at 21:34
  • 1
    If you want to persist your instance variables between postback, you can store them in the ViewState public int MyVal{ get{ return (int)ViewState["__MyVal__"];} set{ ViewState["__MyVal__"] = value; } } – Babak Naffas Jul 07 '09 at 21:37
5

When the page posts back, the Page_Load method is called. Then, once the server actually processes the page and sends you a new one based on changes, the Page_Load is called again, actually the first time on the new page sent to you.

So if you are pulling data in the Page_Load event or setting some values, enclose it in the following block:

if(!Page.IsPostBack)
{

}

to preserve some of your state. Otherwise, the instructions that you put into the Page_Load event will execute every time.

It helps to review the ASP.Net page lifecycle :)

Eugene
  • 2,965
  • 2
  • 34
  • 39
1

As Joel mentioned, instance variables will be lost once the page is sent back to the client. However, there are various methods of storing the values of your variables so you can retrieve them later. This page on State Management is a good starting point if you want to learn more.

tbreffni
  • 5,082
  • 5
  • 31
  • 30
1

This code works for me:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["something"] == null)
        {
            Session["something"] = "1";
        }
        else
        {
            Session["something"] = null;

            //your page load code here 

        }               
    }
}
1

For me, the issue was a bit complicated, but I found that the

protected override void OnPreRender(EventArgs e)

handler is only called once, so it's safer to put some actions in there if it's not too late in the pipeline for you.

David d C e Freitas
  • 7,481
  • 4
  • 58
  • 67
1

An extension of @user3207728's response, I found this link explains it well and has a simple solution...

http://www.aspdotnet-suresh.com/2010/04/detect-browser-refresh-to-avoid-events.html

Unfortunately checking just for if (!Page.IsPostBack) is not enough as IsPostBack will always be FALSE on a refresh.

Fandango68
  • 4,461
  • 4
  • 39
  • 74
1

Any tag/element which requires url reference like img, anchor, object etc must be checked for the empty reference.

e.g. href="", url="", src="" are some common errors.

anand
  • 81
  • 1
  • 9
0

Just a shot in the dark but maybe add this after your page_load:

if (!IsPostBack)
{
Tim Meers
  • 928
  • 1
  • 14
  • 24
-1

you can use sessions or viewstate to retain the values of variables..

  1. if you want to redirect to a different page , use session[]
  2. else if you want to stay on the same page , use viewstate[]
-1

In my Case the Problem Was Related to Iframe, One Time I removed the Iframe Everithing Work Fine

<iframe id="pdf2" 
   src="#"
   width="100%"
   height="100%">
</iframe>
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49