views:

1644

answers:

2

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

+5  A: 

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.

jrista
+1 for mentioning `PreRender` (I neglected to mention it) because it calls `EnsureChildControls` recursively on all children.
Cerebrus
Any guidance though on best practice? With so many events to choose from initially it seems like there's no clear best choice. In particular PreRender vs. control DataBinding event handler. Argh, thank goodness for MVC
Joseph Kingry
Ditto @ MVC. :D As for best practice...start with Load(), and refine as needed. Load() is generally the best place to start unless you know for a fact that you need to bind later, or have a specific reason for triggering the overall page DataBind. Most of the time, if you need to bind in PreRender, its because of an execution and ordering issue that often results when whatever is bound to a control is dependant on some other process completing first.
jrista
A: 

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.

Cerebrus