Question

Is it a "Best Practice" to always use .IsPostBack in the Page_Load sub routine of a web form like in this example coding?

I hope it's ok to ask this question. If not, I will immediately remove the question.

Basically I want to code the way most of you are coding.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Page.IsPostBack Then

        ' More coding will go here.
        '--------------------------
    End If

Please give pros and cons for it's usage.

Was it helpful?

Solution

It's not so much a case of "Best Practice" but more a case of whether you need to use it at all.

It's true, you would normally put IsPostBack in the Page_Load, though you could also put it in the Page_Init - basically in any of the page events that fire before rendering out the HTML.

You're essentially using the command to, in this case, prevent the code in the body from firing when the page posts back to itself; such as a form submission or AutoPostBack on a server control, for example the DropDownList.

There aren't any, at least that I can think of, pro's and con's. Its a case of need or don't.

An example of when you would ideally need it would be only wanting to get data from the database once and bind it to a DropDownList. This data would be available in the viewstate when you postback. so you wouldn't need to visit the database again on postback.

An example of when you wouldn't put code in it is if you were generating server controls (button for example) that have an event handler, such as click, added at the same time. this would need to be re-generated on postback for the event handler to be available.

OTHER TIPS

The benefit is that you can do your expensive operations only once. Binding to gridView...etc.

Mostly stuff you do not want to perform during a refresh.

It always depends on what you want to optimize. If your initialization code takes a long time, it is better to do it only the first time and let your controls be initialize through ViewState. Then you use If Not IsPostBack.

But if you target for mobile devices where bandwidth is more important, you might turn of the ViewState and initialize your data again on postbacks (you could read it from Cache or from SessionState). Always watch your ViewState, I have seen pages with 20 kByte ViewState or more.

Pros:

  • less overhead for initialization (e.g. access to database)
  • less memory on server (session or cache)

Contra:

  • more bandwith for ViewState
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top