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?