Yerg Yerg - 1 year ago 130
ASP.NET (C#) Question

Implementation of IsPostBack in page load

The more I use ASP.NET, the more

if (!IsPostBack) {}
seems pointless...

First example:

For example, I just Googled an issue, they said use this as part of the solution:

if (!Page.IsPostBack)
Page.LoadComplete += new EventHandler(Page_LoadComplete);

Which does exactly as coded, LoadComplete will only fire on the first load. After clicking a button, or anything that triggers a postback, the LoadComplete event is left unhooked, thus skipping the event handler. Therefore, their "fix" only works upon the first load = worthless. I promptly commented out the
if (!Page.IsPostBack) {}
and now the event always triggers as desired.

Second example:

I am attempting to hook events to a dynamically created button (which by the way, I can't get to work [GRR!]). I see examples showing this:

myEditToggleButton = new Button();
myEditToggleButton.ID = "editToggleButton";
//^GOTTA HAVE THIS FOR EVENTS TO WORK! (supposedly, I haven't seen it work...)
if (!IsPostBack)
myEditToggleButton.Click += new EventHandler(myEditToggleButton_Click);

Like the first example, my understanding is that the event wouldn't be hooked after the first page load, thus the button is "inert" after one click (because clicking triggered a postback).


When should you use
if (!IsPostBack) {}
? I am guessing it has to do with mark-up created controls only.

Answer Source

In short, you use it everytime you need to execute something ONLY on first load.

The classic usage of Page.IsPostBack is data binding / control initialization.

   //Control Initialization

Things that are persisted on ViewState and ControlState don't need to be recreated on every postback so you check for this condition in order to avoid executing unnecessary code.

Another classic usage is getting and processing Querystring parameters. You don't need to do that on postback.