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;

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>