Grouping (with Expansion/Collapse) a GridView in C# and ASP.NET or SharePoint


Okay, so developing a UI is fun, especially when there is some challenges to it.

The standard GridView is a very useful dynamic HTML table builder for your data, it can do a lot of different things.  But it is very limited!

For example, if you were to create list that had multiple rows of data, and you wanted to group them by a category, you can’t… …unless that is you add some code.

I took about 3 full days trying to come up with different ways that I can get this done, but I was finally able to figure it out.

image

Now, because I find it better practice, I always find it better to bind the data from the code-behind, rather than pulling in a database directly using the DataSourceObject from the UI.  This makes your application more expandable.

Example:

Sorry, the examples are in images mostly, I will try to format the code so that I can paste it in this form.  But this example I find it important to show where the code should be pasted.

First, make a private list of a string, i called it ItemsToExpand, then initiate it.

image

Next, you will want to save the state of the items expand, and recall them if they contain any values…

image

Before saving the values, you will want to check if it is a postback, and if so, get the values from the EventArguments var that is passed back from the JavaScript client side.

 image

Sort the list, set the data source to the DataGrid, then save the state of the ViewState “ItemsToExpand”

image

Here is what I used to sort the list…

image

Here is the code to create the columns and does all of the magic..

protected override void Render(HtmlTextWriter writer)
{
    Table table = (Table)this.GridView1.Controls[0];

    string lastCategory = string.Empty;

    foreach (GridViewRow row in GridView1.Rows)
    {
        int realIndex = table.Rows.GetRowIndex(row);
        string currentCategory = this.GridView1.DataKeys[row.RowIndex].Values[0].ToString();
        if (currentCategory != lastCategory)
        {
            GridViewRow groupHeaderRow =
                new GridViewRow(realIndex, realIndex, DataControlRowType.Separator,
                   DataControlRowState.Normal);

            TableCell newCell = new TableCell();
            newCell.ColumnSpan = this.GridView1.Columns.Count; // <— Is not working…
            newCell.BackColor = System.Drawing.Color.FromArgb(233, 229, 229);
            newCell.ForeColor = System.Drawing.Color.DarkGray;
            newCell.Font.Bold = true;
            newCell.ColumnSpan = 4;

            bool itemFound = false;
            foreach (string item in this.ItemsToExpand)
            {
                if (item.Trim() == currentCategory.Trim())
                {
                    itemFound = true;
                    break;
                }
            }

            string image = string.Empty;
            if (itemFound)
            {
                image = "<img src=\"http:\\\\csapp2\\Discipline\\images\\nav_minus.gif\""
                + " style=\"cursor:hand;\" onMouseUp=\"__doPostBack(‘__Page’, ‘Show|"
                + currentCategory + "’);\">&nbsp;";
            }
            else
            {
                image = "<img src=\"http:\\\\csapp2\\Discipline\\images\\nav_plus.gif\""
                + " style=\"cursor:hand;\" onMouseUp=\"__doPostBack(‘__Page’, ‘Show|"
                + currentCategory + "’);\">&nbsp;";
            }

            newCell.Text = image + this.GridView1.DataKeys[row.RowIndex].Values[1].ToString();

            groupHeaderRow.Cells.Add(newCell);

            table.Controls.AddAt(realIndex, groupHeaderRow);
            lastCategory = currentCategory;
        }
    }

    base.Render(writer);
}

 

Now, create a RowDataBound Event, and use the example code…

image

You can have multiple data key names, I used two of them in the aspx code.

image

Hope this helps!

 

Bill

Categories: SharePoint or Custom Development | 14 Comments

Post navigation

14 thoughts on “Grouping (with Expansion/Collapse) a GridView in C# and ASP.NET or SharePoint

  1. mskr

    hi
    Can u plz post the javascript also used for……..
    “EventArguments var that is passed back from the JavaScript client side.”

  2. rupali

    Hi,

    can u mail the entire code along with html?
    thanks,
    Rupali

  3. karthik

    Hi Bill,

    Thanks for the post. I have the same scenario but I am using DevExpressGrid.
    Could you check the below URL for my question.

    http://stackoverflow.com/questions/6054499/enable-checkbox-on-call-over-in-devexpress-grid

    Thanks in advance…

  4. Luis

    Working on it, thanks for thee ideas!

  5. Luis

    Almost done but I need to see how the JS looks like. Please post it. Thanks again!

  6. sheela

    Hi,

    Very nice article!! I was looking for this from last two days . Can you please post or email the javascript ? I am new in .net development . I have done all the other steps you mentioned above .

    Please post javascript for this .
    Thanks in advance!

  7. Nixan

    Can you provide code for this post?

  8. Hi,

    Thanks for the post…
    can you please send me the code and javascript for this.

    TIA

  9. shweta

    i want to do same as shown in this.But im not getting how to impement.will u plz send me the code for this.

  10. Nixan

    can you post the entire code please?

  11. Vijay Kumar

    Hi,
    Very happy to see your blog, could you please send the complete source code or upload here so that everyone can download it…. Please send the complete source code to my email id.

  12. Nav

    Hi, could you please send the javascript ‘Show|”+ currentCategory to my email id.

    Thanks
    itsnavanee1975@gmail.com

  13. HI Bill,
    I think if we use SPGridview we can have Grouping in that by default.

    http://www.aboutsharepoint2010.com/2012/03/spgridview-groupby-column-name/

    please let me know

    Thanks
    RAM

  14. net grid

    Its very helpful information thanks more detail you can visit dapfor. com

Leave a Reply

Fill in your details below or click an icon to log in:

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

Blog at WordPress.com. The Adventure Journal Theme.

Follow

Get every new post delivered to your Inbox.

Join 33 other followers

%d bloggers like this: