Saif Khan
Saif Khan

Reputation: 18792

page load() or page init()

In asp.net, when do you bind your gridviews? at Page Load() or Page Init()....why?

Upvotes: 16

Views: 18132

Answers (2)

Cerebrus
Cerebrus

Reputation: 25775

It would depend on the particular case, however, the most common answer would be Page_Load because that is generally sufficient for most databinding scenarios.

Even for complex databinding scenarios, Page_Init would not be an appropriate place because container controls like the GridView load their children only during the Page_Load event. You need to go farther down the life cycle to access those children.

In my case, however, the answer would be "neither". This is because I never databind a control directly within Page_Load. What I instead prefer is to have a separate method which does the databinding and can be called from Page_Load or any other function if I need to re-bind after postbacks.

Upvotes: 4

jrista
jrista

Reputation: 32960

You should generally bind at or after Load(). The Init() event is intended to allow you to create any dynamically created controls before binding occurrs, so that they exist when binding needs to take place. Load() is not the only option, however...if you need to delay binding on a control for whatever reason, you can also bind in the PreRender() event. It is also possible to do further setup in Load(), call the pages' DataBind() method, and handle the page binding events to bind in an even more structured way, if you need to.

Upvotes: 13

Related Questions