In asp.net, when do you bind your gridviews? at Page Load() or Page Init()....why?
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.
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.