Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .IsPostBack in the Page_Load sub routine

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.

like image 218
Emad-ud-deen Avatar asked Dec 09 '22 19:12

Emad-ud-deen


1 Answers

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.

like image 199
Darren Wainwright Avatar answered Dec 11 '22 08:12

Darren Wainwright