我的页面上有一个带有搜索按钮的 GridView。 GridView 一开始是不可见的,因此用户必须单击“搜索”才能检索结果。 DataSourceID 设置为 ObjectDataSource 的 ID。当调用 click 时,将从单击处理程序中调用以下方法:
private void PopulateGrid()
{
gv.Visible = true;
gv.DataBind();
}
从 Page_Load 处理程序调用相同的方法时会出现问题。我们将用户的搜索词存储在他们的 session 中,并在第一次访问页面时检索它们,如下所示:
if(!PostBack && Session["search"] != null)
{
SetSearchFromSession();
PopulateGrid();
}
本例中的问题是 ObjectDataSource 的 Selecting 事件被触发两次。当 GridView 变为可见时一次,当调用 DataBind() 时再次一次。我通过替换 gv.Visible = true
; 解决了这个问题对于 Page_Load 中的 PopulateGrid();
。
但我想了解发生了什么事。为什么将 GridView 设置为从页面加载可见会导致数据绑定(bind),而按钮单击事件中的调用却不会?
最佳答案
如果您以声明方式设置 datasourceid,那么它将在 PreRender 之后被调用,如果您调用 DataBind,它将再次被调用。 (两次)
DataBinding
Raised after the control's PreRender event, which occurs after the page's PreRender event. (This applies to controls whose DataSourceID property is set declaratively. Otherwise the event happens when you call the control's DataBind method.)
This event marks the beginning of the process that binds the control to the data. Use this event to manually open database connections, if required, and to set parameter values dynamically before a query is run.
关于asp.net - 何时在 ASP.NET 页面上自动调用 DataBind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9606129/