Sep 23, 2009

SPGridView Paging and Filtering

A common issue with SPGridView is to enable paging: the PagerTemplate property of SPGridView needs to be set as null. If the SPGridView is declaratively defined in aspx page, the following code won't enable paging:

<sharepoint:spgridview id="SPGridView1" runat="server" >
<pagertemplate ></pagertemplate>
</SharePoint:SPGridView>

instead the following code works:

protected override void OnLoad(EventArgs e)
{
SPGridView1.PagerTemplate = null;
}

After paging is enabled, another common issue is, filter is off after navigating pages. I know filter is off acturally on every subseqent postback, like sorting. But to some degrees, it makes senses to turn it off since users are given no indication that a filter is on otherwise, which can certainly cause some confusion. But turning filters off on paging is very unsatifactory.

Inspired by the idea in this post, here is what I did to enable filtering across pages (based on .Net 3.5):

first cache filter settings :

protected override void OnPreRender(EventArgs e){


ViewState["FilterExpression"] = ObjectDataSource1.FilterExpression;


base.OnPreRender(e);


}


secondly, set filterexpression when postback is from pagings:


protected override void CreateChildControls() {


arg = (string)req.Form["__EVENTARGUMENT"];
if (arg.StartsWith("Page$") && ViewState["FilterExpression"] != null)


ObjectDataSource1.FilterExpression = ViewState["FilterExpression"].ToString();


}



related reference:


http://geekswithblogs.net/mnf/archive/2005/11/04/59081.aspx (.Net 2.0)


http://forums.asp.net/p/1067215/1067215.aspx (.Net 3.5)