SPGridview and Collapsed Grouping by Default

This really bugged me when I came across the SPGridView (as you can read in the previous about this control) that when you set the following properties

oGrid.AllowGrouping = true;
oGrid.AllowGroupCollapse = true;

You’d expect that there is another property where you can specify if you want to have it collapsed or expanded when the Grid gets rendered. Unfortunately there isn’t.. but (and that’s why I’m posting ;)) there is dirty way to do it and that’s injecting some javascript after the grid gets rendered. Thanks to the following bit of script gets the job done.

<script type="text/javascript">
var rows = document.getElementsByTagName('tr');
var numRows = rows.length;
for (var i = 0; i < numRows; ++i)
{
    if (rows[i].getAttribute("isexp") != null && rows[i].getAttribute("isexp").toLowerCase() == "true")
    {
          if(rows[i].firstChild.firstChild != null && rows[i].firstChild.firstChild.tagName.toLowerCase() == "a")
          {
              if (rows[i].firstChild.firstChild.title.toLowerCase() == "expand/collapse")
                  {
                    rows[i].firstChild.firstChild.fireEvent("onclick");
            }
          }
    }

}
</script>

To explain it the script.. an event called “ToggleSPGridViewGroup” (which can be found in the spgridview.js in the Layouts folder) is fired when you click on the expand/collapse icon on the grouped item. So I thought “Why not fire all of the links to have it all collapsed by default?” 🙂 I thought this wasn’t possible since it seems REALLY dirty to actually fire events without user interaction. But it actually is possible! Thank god 😉

Advertisements

About Joseph Velliah
As a SharePoint Developer my professional interests tend to be technical and SharePoint focused. I run a blog at "SP RIDER" where you can expect to read HOW TOs and scenarios that I run into during my day to day job. I hope my posts will give back a little to the community that is helped me.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: