Paging error when programmatically adding gridview.

When adding the gridview programmatically to a webpage / composite control, you must add the gridview to the controls heirachy before databinding. If you do not, paging breaks giving the error: “ERROR: Object reference not set to an instance of an object.”

Im pretty sure that this is only the case when the gridview datasource is set by the “datasource” property and not by refering to a sqldatasource control using the “datasourceid” property. I experienced this problem when trying to use a mysql datasource.

The code below illustrates the correct ordering:

DataSet ds = CustomGetDataFunction();
GridView grid = new GridView();
grid.AllowPaging = true;
grid.PageIndexChanging += new GridViewPageEventHandler(gridPageIndexChanging);
grid.DataSource = ds;
this.Controls.Add(grid);
grid.DataBind();

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.