I wanted to use a little SPGridView in a software and had a little problem. First of all, in order to use filtering on a SPGridView, you have to give an ObjectDataSource by it’s control’s ID. For anything else, you can use the DataSource property directly.

The best sample code I could fin on the net was this one : Creating the SPGridView with sorting and adding filtering.

This example is great because it only shows the basic requirements to setup a SPGridView and it gives you a clean way to build the ObjectDataSource and it explains step by step why you have to do things this way (in Sharepoint, it’s very important).

The problem, and this is the subject of this post, came when I activated the filtering functionnality. The menu displayed and then got stuck on “Loading…” with an alert message saying it got a NullReferenceException. Here is the pic :

I finally found the origin of my problem. In my first version, I was giving the DataSource to my SPGridView on the PreRender loading step. For the AJAX call, you never reach this step, you have to give the DataSource sooner.

Once I got that right, I just cached the last DataSource in the ViewState to give in the CreateChildControls method and it worked. The menu was finally displaying fine.

It can’t exactly give you my code (because it’s not legally mine), but here is the basic idea:

In the real world usage, you will give your DataTable to a property so that it can be displayed later by your SPGridView. So you can basically just copy/paste the ASPGridView class given by Erik Burger and just replace the SelectData method by this one:

public DataTable SelectData {
    return DataTable;
}
 
public DataTable DataTable {
    get {
        return ViewState["DataTable"] as DataTable;
    }
    set {
        ViewState["DataTable"] = value;
    }
}

And anywhere in your WebPart’s OnPreRender method, or in any button’s event receiver method, you could build your DataSource.