16

在 asp.net 中,你什么时候绑定你的 gridviews?在 Page Load() 或 Page Init() .... 为什么?

4

2 回答 2

13

您通常应该在 Load() 处或之后绑定。Init() 事件旨在允许您在绑定发生之前创建任何动态创建的控件,以便在需要进行绑定时它们存在。Load() 不是唯一的选择,但是……如果您出于某种原因需要延迟对控件的绑定,您也可以在 PreRender() 事件中进行绑定。如果需要,还可以在 Load() 中进行进一步设置,调用页面的 DataBind() 方法,并处理页面绑定事件以更加结构化的方式进行绑定。

于 2009-06-02T16:21:21.630 回答
4

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.

于 2009-06-02T16:26:53.783 回答