Saturday, May 9, 2009

SPGridview Grouping. Is it easy to apply??

Well, have you ever tried to create new sharepoint webpart with SPGrdiview and tried to enable grouping??

For the first time you call your grid it will work fine, but if you tried to use it in searching page(like you have textbox and submit button to bind the data to your grid based on entered text), it will come up with annoyed ASP.NET yellow error page saying:

" System.ArgumentNullException: Value canot be null "

the problem happened while rendering the rows again after the postback.
To solve this problem follow the steps below:
  1. Create new class @ your webpart project calling "SPGridViewGrouping".
  2. Let this class inherits from "SPGridview", your class should look like this:

    class SPGridViewGrouping : SPGridView
    {
    protected override void LoadControlState(object savedState)
    {
    base.LoadControlState(savedState);
    if (this.DataSource == null)
    {
    this.InvokeRequiresDataSource();
    }
    }
    public event EventHandler RequiresDataSource;
    private void InvokeRequiresDataSource()
    {
    //throw new NotImplementedException();
    EventHandler handler = this.RequiresDataSource;
    if (handler != null)
    {
    handler(this, new EventArgs());
    }
    }
    }
  3. At your webpart class create your grid object from "SPGridViewGrouping" NOT "SPGridview".
    SPGridViewGrouping oGrid = new SPGridViewGrouping();
  4. Add handler calling your menthod created @ SPGridViewGrouping
    oGrid.RequiresDataSource += new EventHandler(oGrid_RequiresDataSource);
  5. At this handler will look like:
    void oGrid_RequiresDataSource(object sender, EventArgs e)
    {
    //throw new NotImplementedException();
    oGrid.DataBind();
    }
  6. Enjoy your grouping.