Colin
Colin

Reputation: 22595

When is DataBind called automatically on an ASP.NET page?

I have a GridView on a page with a search button. The GridView is not visible to start with so that the user must click search before results are retrieved. The DataSourceID is set to the ID of an ObjectDataSource. When click is called, the following method is called from the click handler:

private void PopulateGrid()
{
    gv.Visible = true;
    gv.DataBind();
}

A problem occurs when the same method is called from the Page_Load handler. We store a user's search terms in their session and retrieve them the first time the page is accessed, something like this:

if(!PostBack && Session["search"] != null)
{
   SetSearchFromSession();
   PopulateGrid();
}

The problem in this case is that the ObjectDataSource's Selecting event is fired twice. Once when the GridView is made Visible, and again when DataBind() is called. I fixed this by substituting gv.Visible = true; for PopulateGrid(); in Page_Load.

But I'd like to understand what is going on. Why does setting GridView visible from page load result in DataBinding when a call in a button click event doesn't?

Upvotes: 2

Views: 6369

Answers (1)

O.O
O.O

Reputation: 11307

If you declaratively set the datasourceid then it is going to get called after PreRender and if you call DataBind it will be called again. (twice)

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

Upvotes: 2

Related Questions