GridView not Rebinding Properly After Postback

Jason N. Gaylord picture Jason N. Gaylord · Nov 18, 2009 · Viewed 26.2k times · Source

I have a GridView that has a DataSourceID pointing to an ObjectDataSource. The ObjectDataSource points to a method that returns a LINQ IQueryable by using the TypeName, SelectMethod, and SelectCountMethod properties of the ObjectDataSource control. What happens is that the data loads properly upfront. However, on postback, if I remove the rows from the GridView and try to rebind using the explicit GridView.DataBind(), it doesn't work. I know LINQ is returning the proper rowcount and such because I've called the countmethod and it returns the proper rowcount. Here's a quick example:

<asp:GridView ID="TestGridView" runat="server" PageSize="20" 
    AutoGenerateColumns="false" AllowPaging="true" 
    AllowSorting="false" DataSourceID="TestDataSource">
    <Columns>
        ...
    </Columns>
</asp:GridView>

<asp:ObjectDataSource ID="TestDataSource" runat="server" 
    EnablePaging="true" SelectCountMethod="GetDetailCount" 
    SelectMethod="GetDetails" TypeName="MyApp.PageClass" />

I've tried adding a button and adding the TestGridView.DataBind(); method to that. I've tried adding it to the Page_PreRender event. No matter what I try, it's not working.

As someone suggested below, I've tried moving it to Page_Load as well, and no go. Here's a rough example of my code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // Set "initial" query parameters, then ...
        BindData();
    }
}

private void BindData()
{
    // EDITED: Removed the code below since I'm not looking to delete the
    //         rows from the database, but rather get the GridView to rebind
    //         which its not.
    ////Remove all current rows from the GridView
    //int colCount = TestGridView.Rows.Count;
    //for (int x = 1; x <= colCount; x++)
    //{
    //    TestGridView.DeleteRow(x);
    //}

    // Bind GridView to the ObjectDataSource
    TestGridView.DataBind();
}

protected void RegenerateImageButton_Click(object sender, ImageClickEventArgs e)
{
    // Set "updated" query parameters, then ...
    BindData();
}

Answer

Sprintstar picture Sprintstar · Aug 18, 2010

Gridviews are not re-bound on postback, their rows are pulled back from viewstate. Resetting the gridview's DatasourceID to the object data source ID on page load (or init?) will cause the gridview to be rebound.