In asp.net, when do you bind your gridviews? at Page Load() or Page Init()....why?
The Page_Init event is the first to occur when an ASP.NET page is executed. This is where you should perform any initialization steps that you need to set up or create instances of server controls.
Page_Load() method is called after a preLoad event. With Page_Load() you can set default values or check for postBacks etc. protected void Page_Load(object sender, EventArgs e) { int x = 10; } write this and put a break-point on int x = 10; watch sender and e.
The Viewstate is actually loaded in the OnPreLoad event of the page,Just after the Page_InitComplete.
In ASP.NET, a web page has execution lifecycle that includes various phases. These phases include initialization, instantiation, restoring and maintaining state etc. it is required to understand the page lifecycle so that we can put custom code at any stage to perform our business logic.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With