Grouped SPGridview Exceptions
Yesterday I spent many hours trying to solve what should have been a simple issue - grouped views in a SPGridview.
I was building a web part that used an embedded SPGridview - this was part of a template I created used by a TemplateBasedControl which was the created by the Web Part. All was working fine until I decided to add grouping. I set the GroupField, AllowGrouping, and AllowGroupCollapse properties:
<SharePoint:SPGridView AutoGenerateColumns="false" runat="server" ShowHeader="true" ShowFooter="true"
GroupField="GroupField" AllowGroupCollapse="false"
AllowGrouping="true" DisplayGroupFieldName="false"
ID="inventoryGrid" AutoGenerateDeleteButton="false" AutoGenerateEditButton="false"
AutoGenerateSelectButton="false">
The control rendered fine until a postback happened - then I started getting exceptions, relating to SPMenuField. Since I was not creating a SPMenuField I was confused. After much digging I came across some helpful hints - pointing to postback issues with SPGridview.
Of particular help was http://www.thesug.org/blogs/patrickr/Lists/Posts/Post.aspx?ID=2 . However I simplified my code down and it seemed to work for me. My solution involved creating my own Class derived from SPGridview and then overriding the LoadControlState method as shown in the above post but since my control was being used in a webpart and I cannot modify the page - I just called DataBind directly:
So my class code looks like:
public class LTCSPGridView : SPGridView
{
protected override void LoadControlState(object savedState)
{
base.LoadControlState(savedState);
if (this.DataSource == null)
{
this.DataBind();
this.InvokeRequiresDataSource();
}
}
public event EventHandler RequiresDataSource;
protected void InvokeRequiresDataSource()
{
EventHandler handler = this.RequiresDataSource;
if (handler != null)
{
handler(this, new EventArgs());
}
}
}
My modified Template definition then looks like:
<ltc:LTCSPGridView AutoGenerateColumns="false" runat="server" ShowHeader="true" ShowFooter="true"
GroupField="GroupField" AllowGroupCollapse="false" AllowGrouping="true" DisplayGroupFieldName="false"
ID="inventoryGrid" AutoGenerateDeleteButton="false" AutoGenerateEditButton="false"
AutoGenerateSelectButton="false">
This fixed my problems - I hope it helps someone else.
Ian.