asp.net - 何时在 ASP.NET 页面上自动调用 DataBind?

标签 asp.net data-binding gridview objectdatasource

我的页面上有一个带有搜索按钮的 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.

source

关于asp.net - 何时在 ASP.NET 页面上自动调用 DataBind?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9606129/

相关文章:

javascript - 如何使用 ASP.NET MVC4 Razor 项目中 web.config 文件的值更新 JavaScript?

asp.net - 强制站点使用 SSL(通过 IIS)导致 WebResource.axd 加载问题

wpf - 将 List<string> 绑定(bind)到 GridViewColumn

c# - 数据绑定(bind)动态数据

c# - 使用数据绑定(bind)的 C#/WPF 中具有确定/取消行为的对话框

Android GridView 重复图像

c# - ServiceStack ResponseFilterAttribute 未被调用

gridview - 如何在GridView.builder内部的内容之间显示AdMob原生广告?

WPF:如何以编程方式设置 ListView 的样式,以便所有行都具有特定的背景颜色和高度?

c# - WebAPI 全局异常处理