SPGridView and SPMenuField: Displaying custom data through SharePoint lists

Part 1: Using SPGridview, adding menus, grouping and sorting

Click along to build this lovely Web Part, taking data directly from a standard .NET DataSet:

SharePoint lists and libraries are great for storing almost everything, but what about if you need to display structured lists in SharePoint where the data is stored elsewhere?  If you use Office SharePoint Server (MOSS), one great feature for this purpose is the Business Data Catalogue.  However, if you only have Windows SharePoint Services (WSS), or need to dynamically construct data, chances are you'll end up needing to write a Web Part.

Web Parts give you some standard look and feel elements for free, like the ‘crome' or border, plus an ability to add your own properties to the properties grid.  After that, you're pretty much on your own.  Wouldn't it be nice if you could display your own data in a sexy SharePoint list?

SharePoint uses the Microsoft.SharePoint.WebControls.SPGridView control to display its own lists.  This class inherits from System.Web.UI.WebControls.GridView, so the development experience to bind data, adjust columns, perform sorting etc is similar.  The key difference is the control renders the grid in the SharePoint style - perfect.

Create a Web Part

Any blank Web Part will do - you could use the template provided by Visual Studio if you have the SharePoint SDK installed.  My web part started out life like this:

using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace ListMenuSample
public class ListMenuSample : System.Web.UI.WebControls.WebParts.WebPart
private SPGridView oGrid;
private TVData oDataset;
private DataView oView;

private void PopulateDataset()

protected override void CreateChildControls()

void oGrid_Sorting(object sender, GridViewSortEventArgs e)


Create the data source

In this example, we'll create and populate a dataset and use it for data binding.  I want a list to keep track of who presents my favourite BBC current affairs programmes, so I'll design and populate a DataSet accordingly.

If you want to bind your SPGridView back to SharePoint data, that's simple too, check out this great article from Share This Point.

My DataSet, TVProgrammeData has a single table, Presenters, comprising an int and two string columns:

We'll fill the DataTable from code, but obviously you'd want to pull this from somewhere, probably SQL, a filesystem, a web service or XML.  Pop this into the PopulateDataset() method.

private void PopulateDataset()
= new TVData();
1, "Jeremy Paxman", "Newsnight");
2, "Kirsty Wark", "Newsnight");
6, "Bill Turnbull", "Breakfast");
7, "Sian Williams", "Breakfast");
// plus a few more entries

Render the Grid

Overriding CreateChildControls() is a good place to create your SPGridView and add it to the controls collection.  You'll also need to bind up the columns and specify sorting.  To give us magical sorting abilities, we'll bind to a DataView rather than directly back to the DataTable.  Pop this into CreateChildControls():

protected override void CreateChildControls()
= new DataView(oDataset.Presenters);

oGrid = new SPGridView();
= oView;
= false;
= true;
+= new GridViewSortEventHandler(oGrid_Sorting);

BoundField colName = new BoundField();
= "PresenterName";
= "Presenter Name";
= "PresenterName";

// Add the menu control here

BoundField colProgramme
= new BoundField();
= "ProgrammeName";
= "Programme";
= "ProgrammeName";



Notice we specify the SortExpression to use, which together with AllowSorting enables users to order the results by clicking the columns headers.  We need to perform the sort ourselves though, through the event handler; and we'll need to keep track of the sort direction in ViewState so we can flip it next time the user clicks the same header.  I'm not sure my code is very elegant in this area, so leave a comment if you can think of a better way to do it in fewer lines of code.

Add this event handler:

void oGrid_Sorting(object sender, GridViewSortEventArgs e)
string lastExpression = "";
if (ViewState["SortExpression"] != null)
= ViewState["SortExpression"].ToString();

string lastDirection = "asc";
if (ViewState["SortDirection"] != null)
= ViewState["SortDirection"].ToString();

string newDirection = "asc";
if (e.SortExpression == lastExpression)
= (lastDirection == "asc") ? "desc" : "asc";

ViewState["SortExpression"] = e.SortExpression;
"SortDirection"] = newDirection;

oView.Sort = e.SortExpression + " " + newDirection;

If you build and deploy this web part, you should get something like this (see this post for tips on the debugging process):


That looks alright, and it will adapt correctly if you apply different style sheets, themes or a new master page.  But it's still not a very rich interface.  How about if you wanted users to edit items, or get more detail.  Umm, better add a menu.

Add a menu

It's worth pointing out about now that the documentation around this area is still in production - so I'm coding with a slight emphasis on experimentation for some of the property values - I'll point you to the official source when it's revised.

Anyway, SPMenuField is the class we need, and combines the roles of controlling the drop-down menu with the basic display work done by BoundField.  Let's replace our boring colName column with a shiny menu that looks like this:

// Replace the Name coloumn with a shiny menu
colName.Visible = false; // You could remove colName completely

SPMenuField colMenu
= new SPMenuField();
= "Presenter Name";
= "PresenterName";
= "PresenterListMenu";
= "ID,PresenterName";
= "do.aspx?p={0}&q={1}";
= "EDIT=ID,NAME=PresenterName";
= "PresenterName";

MenuTemplate presenterListMenu = new MenuTemplate();
= "PresenterListMenu";
MenuItemTemplate biogMenu
= new MenuItemTemplate(
"Read Biography", "/_layouts/images/EawfNewUser.gif");
= "do.aspx?this=%EDIT%&that=%NAME%";
//entry.ClientOnClickScript = "your javascript here";

MenuItemTemplate broadcastMenu = new MenuItemTemplate(
"Recent Broadcasts", "/_layouts/images/ICWM.gif");

MenuSeparatorTemplate sepMenu = new MenuSeparatorTemplate();

MenuItemTemplate favMenu = new MenuItemTemplate(
"Add to Favorites", "/_layouts/images/addtofavorites.gif");


Tip: You can have a poke around the standard icon collection and pick some suitable images from C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\IMAGES

SPMenuField serves two purposes - it configures the hyperlink you follow if you click on the item directly and, optionally, links to a snazzy dropdown menu.

This great post at SharePoint Solution Blog gives a good overview of how to extend the Admin interface with custom menus.  However, the difference with custom menus on list items is that you're not creating one - you're creating one for each list item, and your menu handling routine needs to know which item you clicked in.

Fortunately, there are a few ways to achieve with.  First we setup colMenu to pass in the required parameters when you click on the main item hyperlink:

Here, NavigateUrlFields is a comma-separated list of data bound items we want to use in the URL.  Then we replace placeholders starting at {0} with the items in sequence.

Next, we need to decide how to respond to clicks on the drop-down menu.  We have two options here - build a click URL similar to the one above, or use our own javascript.  We might have a third option to do a sexy postback to an event in the code behind, but I can't decipher exactly how to use that yet - keep tuned.

The URL way uses a modification in syntax but essentially the same principle as above.  This time we name the data fields we want and then consume them within % signs on the menu items:

Let's finish off for now by adding some grouping (and a few more presenters):

oGrid.AllowGrouping = true;
= true;
= "ProgrammeName";
= "ProgrammeName";
= "Programme";

Leave a comment if you've found this useful, and particularly if there's anything else you'd like to see added.


Comments (102)
  1. Paul Robinson has posted an interesting article about using SPGridView control to view custom data. …

  2. st3ph3n says:

    Excellent article Paul. Can’t wait for the next part.

  3. Using a SPGridView inside an ASP.net Ajax UpdatePanel

  4. fishwack says:

    Hey thanks for the info about how to do sorting and adding the menus. Works great and me some time 😀 Just a note if you do the paging, in Jasons post, you have to also set the SortExpression in your Paging event handler.

    I just put up a new post on using the SPGridView in an ajax updatepanel to do paging and sorting ajax style. Pretty cool stuff.



  5. Paul Robinson says:

    That sounds great Mark, can you post the URL – I notice you’ve had a clipboard accident!

    Glad people found this helpful – I’m gathering information on filtering etc for the next post.


  6. hardeep says:

    This is Great!

    I tried your sample but the drop down menu is not showing up. It shows the down arrow and the link on the list item itself is working but not the drop down menu. Any tips/fixes?



  7. Paul Robinson says:

    Umm, sounds interesting. Why not drop me an email with your code – there’s an email link at the top.

  8. mdo77 says:

    "We might have a third option to do a sexy postback to an event in the code behind, but I can’t decipher exactly how to use that yet – keep tuned."


    Any developments here?  It would make my job 1000% easier if this were to work.  I’ve got to make some web service calls depending on what option is selected in the dropdown and it would be a great deal easier if I could do it in the web part class itself during pre-render.



  9. mdo77 says:

    of course, I meant Pawlo above, not paul.  My apologies.

  10. Paul Robinson says:

    Hello everyone,

    Thanks for the comments.  I’m on residential training in Redmond for a couple of weeks, which is consuming all my time.  I will answer your comments as soon as I can, probably next week when I’m back in the UK.  Please post any solutions if you get things working in the meantime.

    I’m committed to taking this forward, and I’m now working with a very helpful contact in the WSS documentation team to find answers to the various bits and bobs.


  11. Good article shows how to use SPGridView and SPMenuField. However seems SPMenuField still cannot help

  12. groovyponens says:


    first at all, congratulations for the article. I have been following it in a custom web part.

    I have a big doubt about SPGrid, i wish someone could help me. I don’t know how to do to show a Linked Name to details page in the grid. I have tested with LinkTitle, LinkTitleNoMenu, . All of these fields return me the title of the element but not a link to details page as i want. ¿Do you know how have i to do it?

    Thanks, very much,


  13. Paul Robinson says:


    I’m not entirely sure what you’re trying to do.  You’re in full control over the SPGridView, so if you want your items to have a details page behind them, you’d need to code this in.  Why not drop me an email (use the email link at the top) with more info.


  14. dmetge says:

    Hi… great post !

    But I’ve got the same problem Hardeep already mentionned : the drop down menu is not appearing (but the down arrow of the menu appears on the items of the list). Hardeep, did you finally solve the problem ? Or Paul, did you find a solution or an idea about it ?

    Thanks in advance


  15. Skullcrusher says:

    Hi Paul great article, certainly saved me some time.

    I have a couple of questions that you might be able to help me with.

    1) Is there an easy way to have the groups collapsed when first rendered?

    2) Can you have multiple level grouping?  I know this should be possible as with lists you can create views that allow 2 levels of grouping.

    Any insights would be appreciated.



  16. Paul Robinson says:

    Hi Andy,

    I don’t know of a way of showing the grid with the groups already collapsed and I’m not sure about the two levels of grouping either.  Looking at how the fields/grouping parameters are passed I can’t see how this would be achieved.  Let me have a hunt around.

  17. Paul Robinson says:


    When Hardeep sent me the code my was using it was pretty complex, as he had already extended the example with his own business logic.  My advice, which I think worked, was to comment most of it out (!) until he got back to simple code, then check each property I was setting in the example was also set by his code – I’m pretty confident it will work if everything’s in the right order!


  18. Skullcrusher says:

    Hi Paul

    I’ve managed to figure out a way to collapse the groups when first rendered, through some javascript that I’m registering with the page from within my webpart, I’ll blog it next week.

    As for the multiple grouping levels I’m still trying to fathom that one out 8-}


  19. jay.arvin.s.gamiao says:

    Nice blog!  I do have one question though.  Have you tried adding webcontrols in the SPGridView just like the GridView in ASP.Net.  Like for example, I would like to have a Checkbox, Image and a linkbutton and when you click on the linkbutton, it would open the item and execute a stored procedure?

    Jay Arvin

  20. c05lc31 says:

    Its great article. I am need to sharepoint and wanted to find out if you have the code as to What TVData looks like



  21. dmetge says:

    Hi Paul,

    Sorry I’m back with the same problem again (the problem Hardeep already mentionned too) : I’ve made a webpart using exactly your code this time, but again it doesn’t work : the SPGried is appearing and the down arrow of the menu is appearing on each item, but the drop down menu never appears when I click the arrow.

    As I’m sure now it can’t be a problem in the code, could it be a contextual problem ? I mean, something else on the page (or the site) preventing the menu’s script to work ?

    Did you or someone already heard about it ?

    I’ve simply created a collection and a site, and put my webpart on the first page of the site. Furthermore there is no other webpart on the page. I don’t know what I could try now. Voodoo things ?!

    Thanks in advance !


  22. I recently chose to use this control in a scenario where filtering using the UI was required. I had heard about the SPGridView and knew it had the filtering capabilities I needed, but I had a very hard time figuring out how to use it. But after much (unsuccessful)

  23. Great news everyone o/ – a solution to setting an SPGridView filter has been researched and documented

  24. hardeep says:


    Sorry for the late reply. I didn’t visit this blog for a long time. Actually I got the drop downs working a while ago. The code was missing one thing:  base.Render(writer); within the webpart Render method. I added that and it worked!!


  25. ArjunaK says:

    Thanks Powlo and Hardeep!

    I was also having the same issue and base.RenderWebPart(writer) rendered the drop down menu nicely.


  26. dmetge says:

    Thanks a lot Hardeep,

    indeed, a base.Render(writer) instruction is necessary at the end of the webpart’s Render method if we want the items of the menu to appear !

    But there is another solution, too ! Let me explain, it can maybe be useful for someone.

    In fact, the base.Render(writer) calls the RenderControl() method for all the objects added in the createChildControls method (using this.Controls.Add)

    In Powlo’s script there, both the SPGridView oGrid and the menutemplate presenterListMenu are added to the controls of the webpart. So, when we call base.Render(writer) in the Render method, both oGrid.RenderControl(writer) and presenterListMenu.RenderControl(writer) are called !

    So, if you can’t call base.Render(writer), for example in case you have other controls that you don’t want to appear at the same time, you just have to use :



    in the Render() method of your webpart ! Of course, to do this you’ll have to declare both oGrid and presenterListMenu as global properties in the script.

    Then it will work fine, it’s a very logical thing : the menu needs the menutemplate to work.

    Hope it can help !


  27. Paul Robinson says:

    We’re getting some great comments on here – thanks for the advice and community help people!


  28. kalle11 says:

    I have made a webpart based on this code (plus some more functionality of my own, mostly for testing purposes) and everything works, except for the paging.

    I can see the correct nr of records on page one and got the paging menu below and so on, but when I press the "2" to go to next page the page simply refreshes and I’m back at page "1" again, so I can never see the other pages of records. What can cause this problem?

    I tried and commented out all the code associated with sorting thinking that might be causing some problems, but I still can’t see any other pages than the first in the page list.

    I’m new to webpart/asp programming so any help or suggestions would be greatly appreciated.

  29. kalle11 says:

    I just noticed that I posted my last post on the wrong page (should have been in the "part2 – paging article") but as I posted here before I continue to do it also.

    Anyway, I tried another thing in my code and it solved my paging problems. It seems like it’s working as it should now (haven’tested it thorougly yet though) so you can ignore my previous question.

    The change I did was to move the code that added data to the datatable from it’s previous place in the RenderControl method to the beginning of the CreateChildControls method (directly after the "new DataTable" statement.

    It feels like there is something about theese two methods that I don’t really understand, like exactly WHEN they are called and in what order. I thought that CreateChildControls was called the first time the webpart got initialized (like when loading the page where the webpart is located on, thus all the initializing of controls and so on) and that everything else after that regarding visible controls was handled by the RenderControl method. Apparently I was wrong but now I’m really confused.

    So, can any kind person explain when the both methods is being used? I’m trying to get a bigger picture of webparts and how the common methods work, but imo it’s hard to get a good picture of it all and MSDN isn’t really helping out to be honest (they only go into details, not the bigger view that I need to understand how it all relates to eachother).

    Thanks in advance.

  30. Paul Robinson says:


    Glad you got sorted.  There’s some simple info at

    ASP.NET Web Parts Life Cycle  


    but I guess you’re already past that. I remember seeing a very complete version which shows which events fire in which order – a full page of flowcharts – I’ll try and remember where it was and search it out for you.

  31. cfarmerga says:

    I thought I’d share the result of my effort to figure out the postback stuff.  It seems to work well enough for me, and I’m just doing this in an application page instead of a webpart, so YMMV, but the effect should be the same.

    I noticed (via Reflector) in the setter for MenuItemTemplate.ClientOnClickUsingPostBackEvent there was some code to parse parts of this string value, apparently delimited by commas.  Teh first part evaluates to a control name.  I thought this was weird, since I don’t want to simulate clicking on another control.  Then I noticed the special “__page” value that enables you to postback to the containing page.  Perfect.  So, I just implemented IPostBackEventHandler on my derived page class and implemented its single method:

           void IPostBackEventHandler.RaisePostBackEvent(string eventArgument)


               throw new Exception(“WHEEEEEEE! ” + eventArgument);


    Then in my MenuItemTemplate, I set the ClientOnClickUsingPostBackEvent property’s value to “__page,%NAME%”.  When I ran my page and clicked on my menu item, I got my nice error message with the resolved value of the %NAME% token for that list item.

    The moral of the story is that without Reflector, this would have been miserable.  As it was, it took about 45 minutes to figure this out.  It sure would be nice to have some better docs for the lower-level stuff like this, though!

  32. cfarmerga says:

    Slight nit:  Oops.  I meant "application page" when I said "content page."  

  33. Paul Robinson says:

    Thanks cfarmerga – sounds like you’ve got it all sewn up!

  34. cfarmerga says:

    While I’m here, I’d like to know what the best way would be to cause a postback on simply clicking the SPMenuField’s item.  I really want to use the menu field for the cool menu features, but I also want to have the default behavior of clicking the text of my item result in a postback.


  35. Petrander says:

    Hey Paul,

    Great article and just what I was looking for investigating the different possibilities of customizing the powerful SharePoint platform.

    Interesting that there is a special SharePoint version of the GridView control so familiar to regular ASP.NET 2.0 users. One thing that I am missing, though, is an equivalent of the equally familiar DetailsView control.

    Being pretty new to SP I may have overlooked something, but it would really be nice it were possible to display details of a row selected in a gridview on the same page.

  36. timo77 says:

    I Paul,

    grat article, it was very helfull for me, thanks.

    You saved me a saturday night otherwise I’ve spent to think how implement a menu in a column grid 🙂

    I’ve another question.

    How about to implement the ToolBar menu where i can add my custom button and menubutton?

    I’ve tried but it doesn’t work.

    thanks in advance.

    the code for my toolbar:

    [SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true),

       SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)

       //, AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)

       //, AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)


       public class N41SPToolBar : TemplateBasedControl


           [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]

           protected override void CreateChildControls()



               Microsoft.SharePoint.WebControls.ToolBar toolbarControl = (Microsoft.SharePoint.WebControls.ToolBar)this.TemplateContainer.FindControl("toolBarTbl");

               //this.TemplateName = DefaultTemplateName;


               if (toolbarControl != null)


                   //Microsoft.SharePoint.SPCustomActionElement.AddCustomToolbarButtons(this.Web, base.RenderContext.List, null, Microsoft.SharePoint.PAGETYPE.PAGE_VIEW, toolbarControl);

                   this.TemplateControl = toolbarControl;



           protected override string DefaultTemplateName




                   string toolbarTemplateName = string.Empty;

                   if (string.IsNullOrEmpty(toolbarTemplateName))


                       return "ViewToolBar";


                   return toolbarTemplateName;




    the method in my webpart.

    private void CreateToolBar()


               N41SPToolBar toolbar = new N41SPToolBar();

               toolbar.ID = "toolbarlist1";



  37. bobsbonanza says:

    I had heard about the SPGridView and knew it had the filtering capabilities I needed. I managed to get it right and thought it would be nice to share this information with others facing the same challenges I did.

  38. vipintanwar says:

    Can we any number of groupings in the SPGridView Control ?

    Actually , i need to make a web part which looks like this:

    -Web application name1

    — Top level site

     — Subsite 1

     — Subsite 2

    — Top level site 1

     — Subsite 1

    – Web application name 2

    — Top level site

     — Subsite 1

     — Subsite 2

    — Top level site 1

     — Subsite 1

    i.e grouping on the basis of web application , top level site and subsite.

    Can we use SPGridView for it or do we have any other control to make such a web part ?

    or is there any out-of box webpart that can be customized for it ? ANY Idea.



  39. nandini_narvekar@hotmail.com says:


    Is it possible to have summaries for groups for totals. I am hoping they won’t be sorted.



  40. Paul Robinson says:

    hi – I’m still trying to work out whether we can tap into the more advanced things like multiple goruping, counts etc but at the moment it’s a no — sorry

  41. Robin Sharepoint Blog says:

    Blogged you at :


    Thanks alot!

  42. Currently I'm busy with redeveloping some 'old' 2003 webparts and quite often I used a .NET

  43. kasper@nathansen.dk says:


    Thanks for a very good post. I can’t figure out how to get the TVData to work. It tells me that I’m missing an reference in VS.NET – what do I do wrong?

  44. robert321 says:

    Am i missing something that makes the spgridview create links for example: created by columns etc?

    I only get everything in normal text.

    Second question is it possible to get the toolbar that are with lists in normal cases.

    Any help is appreciated.


  45. Robin Sharepoint Blog says:

    For the ones who are looking to automically collapse all the grouping, check out my post http://glorix.blogspot.com/2007/08/spgridview-and-collapsed-grouping-by.html

    It’s, just like SkullCrusher said, a piece javascript that’s been rendered after the grid has been rendered. I’ve gotta get it to work while using the Ajaxwebpart.

  46. ivan2007 says:


    First of all, thanks for this great article.

    According to cfarmerga the Unfortunately I can’t get the MenuItemTemplate.ClientOnClickUsingPostBackEvent is supposed to work.

    Unfortunately I can’t it at work.

    My Webpart implements the IPostBackEventHandler.

    I set the ClientOnClickUsingPostBackEvent property’s value to "__page,%NAME%".

    The problem is that my implemented RaisePostBackEvent method doesn’t get fired. Can someone please help me?

  47. Iko says:

    I read earlier that someone was looking for linking from grid items to a Details page. There is a simple way to do so: in the column definition you turn off the HtmlEncode property, and in the Data you add to the dataset, you can put an <a…nchor tag around the item. Optionally, you can also supply a Source parameter which returns to your current page after an edit operation… HTH

  48. Iko says:

    This is an excellent post (original) and has helped me save a lot of time. I have a nice multi-site task list rollup web part working. Thanks much.

    Now, I tried the same using the SPCalendarView – but for the life of it, I could not find a way to bind some of the columns in the dataset to the Calendar View. When you create a Calendar View for a Task List from within Sharepoint, you are required to specify Time Interval (Start and End) field names, as well as coresponding fields for Monthly View Title, Weekly View Title, Week View Subheading, etc.

    I could not find any properties in the SPCalendarView class that looked like candidates for this kind of mapping. I did find a SPCalendarItem class, and the constructor had pretty much all data fields for a calendar item, but that would mean iterating and manually adding items. Defies the purpose of data binding…plus, I did not find a way of "feeding" the SPCalendarItemCollection to the view control either.

    Has anyone looked into this yet? Any help is greatly appreciated.

  49. Iko says:

    Follow up on previous post: For the SPCalendarView, you actually populate the SPCalendarItemCollection and then use it as DataSource of the SPCalendarView object.

  50. mekrish says:

    Thanks for the good post,

    I am trying to bind the "Type" field of document libray to the SPGridview and my datasource is list(i.e document library). I tried to do as

    HyperlinkField h1= new HyperlinkField();

     h1.DataTextField="Item Type";


    and i got only 1 and 0 on the type field. If the item is folder it shows 1 and if the item is document it shows 0. I want to show the folder icon and document icon in my SPGridview. can you please suggest me any idea..


  51. dmitryvy says:

    Hi All!

    Great article! Does anybody know how to add standard menus to the SPGridView?

    Thanks a lot

  52. SPGridView sorting when using a datasource

  53. robin3000 says:

    Excellent post.  I have built upon your example for creating context sensitive menus based on this example, if anyone is interested.  You can view the blog at http://robin3000.blogspot.com/2007/11/context-sensitive-menus-in-sharepoint.html

  54. bazztrap says:

    I encountered some issue with Grouping.

    SPGRIDVIEw and Objectdatasource objects

    I am implementing this in a web part along with a button to select different views on SPGridView (one of which is grouped view)

    There are different columns for the both the views and 2 common columns which get displayed in both the view.

    The Grid loads up fine with standard view on chnaging to view to Grouped.

    The postback event looks for the new view and I call SPGridView bind

    The Group view Displays fine.

    But now I switch to other or the orignal view non grouped..

    It displays the header correctly… the filter options show correctly but the datarows dont have any column which is new for this view and only shows the previous columns but the data is updated.

    Note these functions work fine with out grouping..

    The interesting thing is if I have 2 grouped views and I change from one to another it takes me to web part maintennace … on SPGridView.DataBind()  the stacktrace leads me to SpWeb object with index out of range exception (WIERD)

    Also as i said binding was done in CreateChild and Postbackevnt.  

    After prerender the Ondatabind event was fired twice ( iguess for 2 times it was called) .. but after moving the view from grouped to non grouped it was fired just once.

    I also moved the SPGrid.DataBind to  Render  Method and took it out from createchild and postback event .. it displayed all the view perfectly ok … but then the header stoped displaying filter details .

    Maybe I am mising somehting .. Anyway if not this I will just overirde  SPgridEvent and manually display groups in old fashion way… this thing shouldnt be that difficult

  55. Paul Robinson says:

    sounds a bit odd – did you get it sorted?

  56. stephaneey says:


    Thanks for sharing this code but unfortunately, it doesn’t work on my machine and I can’t figure out why. The ECB is there but when clicking on the arrow, nothing happens although I made a copy/paste of your code.

    Would it be possible to propose your project in download? or…do you have any idea of what’s going on here?

    Thanks anyway.

  57. bazztrap says:


    I think the problem has something to do with View state and binding between datasource and SPGridView… Something somewhere holds on to something or doesnt get updated..

    I am now using 2 GridViews and 2 ObjectDatasource between different datasource.

    When you have viewstate turned off .. on post back the Filtered Selection does not persist( as expected)  But Sort does persist I think on object datasource .

    all this makes me want to switch to EXtJs.2.0

  58. icop says:


    and thanks for helpful article. Anyone encountered the strange problem with sorting(and filtering) on identical webparts laid on one page with identical data? When you click link on a column’s header on any webpart to sort that column the action is just right but when you do the same sorting from header column’s menu sort action applied to a webpart that is a first on a page.

    Any ideas?

    Thanks in advance.

  59. stephaneey says:


    Just to let you know : the problem I had was because I implemented a custom render method in which I had MySpGridView.RenderControl(writer)….and that’s why the menu was not working properly….

    By the way, another interesting thing would be to know how to filter menu items. So for instance, enabling menu actions according to the data stored in the list item.

    I found out how to impose a certain permission level by using the Permissions property but having a kind of conditional formatting on the menu items looks more difficult.

    Any idea? (how to bind actions to content type for instance, handled by the standard via a feature…=> custom action+registration type combination.)

  60. masha@sweetchild.com says:

    I try to use SPGridView control inside my User Control in order to put it inside SP page. My data source is SP list.

    When I put my user control inside regular aspx page (not under MOSS application), everything works fine.

    When I put the same control inside page layout and create a page based on this layout – spgridview does not show any rows. It calculates number of pages correctly. When I print oGrid.Rows.Count to some label on the same page, it shows the correct number of rows. So – why these rows do not appear ? Any help ??? Any ideas ??? Thanks.

  61. mayur.joshi says:

    HI stephaneey,

    Even i am looking out for a solution to the business problem like you have. Do you have any leads for the same…

  62. The out of the box Search Core Result web part displays search result in a format that is best suited

  63. Using PostBack on SPGridView and SPMe…

  64. shiva_kalluri says:


    In my application I’m using SPGridView, but Ineed multi level grouping.

    Could you please tell me how to do the multi level grouping.

    Thanks in advance.


  65. Paul Robinson says:

    Unfortunately I haven’t found a way to do this yet 🙁

  66. Pankaj76 says:

    Hi Paul,

    It was a great posting and saving my time.

    I have a requirement to give the ClientOnClickNavigateUrl’ on the ‘GroupField’ and ‘GroupDescriptionField’.

    I couldn’t find any posting to help me on this.



  67. Hari2008 says:


    I have enabled Grouping and sorting in SPGridView in my web part.

    I need to sort the items within the Grouped values but for me grouping is done on sorted values.

    Anyone pls help me.



  68. Yanet says:

    Hi Paul, excelent post !!!

    I develop a webpart using SPGridView and SPMenuField like you, and all is rigth, very functional. I use the DataTable component as the source of my GridView but I have a problem: When I specify myMenu.NavigateUrlFields = "ID", an error is displayed: "Field not found: ID". The field ID is contained in the DataTable´s fields…

    I have tried to find a solution but the problem persists..

    I need some help….


  69. Paul Robinson says:

    Hi there.   Have you got any code you can let me have a look at?  It doesn’t need to build or anything – just the .cs.  Use the Email link on the top toolbar to get in touch.

  70. Yanet says:

    Hi Paul, I sent you an message using the Email link as you said me. I hope you can help me, I need it so much..


  71. levah says:

    Hi there. I develop a webpart using SPGridView and I can add hyperlink column, with datasource in hyperlink column in SharePoint list. Problem is in SharePoint hyperlink column. This column type, return value in format "URL, URL Title" (for example "http://localhost, Intranet"), but this value isn’t regular URL.

    Anybody know, how to show SharePoint list hyperlink column, like hyperlink column in gridview?


  72. Paul Robinson says:

    could you try adding a template column and formatting the sharepoint field the way you want it, with <a> tags?

  73. levah says:

    Can you send me example?

    Now I have tihs code:

    BoundField column = new BoundField();

    column.DataField = "URL";

    column.HeaderText = "URL";

    column.HtmlEncode = false;

    column.DataFormatString = "<a href="{0}">{0}</a>";

    column.SortExpression = "URL";


  74. abradley says:

    Great information. Have you had any experience using the SPGridView.AutoGenerateEditButton and the related RowUpdating functionality? I am trying to do this in my web part and the "Update" method never gets called. I think this is because in CreateChildControls I need to re-create my grid, but I am not sure how to get around this. Any pointers would be appreciated.

  75. JosephIM says:

    Hey guys i am using a ascx to builtout all of my controls and sush for a webpart. What i am doing is allow users to dynamically seach for data in sharepoint via 2 dropdown boxes. all workign great. However…

    When i add the SPMenuField to the GridView on post back it fails with:

    "A control with the specified ID ‘PropertyNameListMenu’ could not be found within the scope of the current naming container. "

    I cant get the sharepoint control elements to even be recognize in VS if i try to build the control directly into the ascx. which is just an added layer of frustration.

    How can i get around this, its been 2 weeks i have been on this issue and i cant resolve it. At this point my code looks like a 5 year old wrote it from me trying every imaginable hack i could think of to get this working.

  76. jajalc@gmail.com says:

    This is too good.. Thanks for this.. really appreciate your effort

  77. Custom webpart vs. SharePoint Designer XSLT

  78. If you would like to have some paragraphs translated from Polish to English please leave a comment. Post

  79. Nie raz już w różnych przypadkach podawałem wam linki odnoszące się do SPGridView , pora się temu trochę

  80. el_topo says:

    Great article.

    Has anyone tried/succeded in selecting a row from the grid that is on the other page (so the application changes page index to proper one and selects proper row)? I wasn’t able to get this working with all the paging/sorting/filtering in spgridview…

    Could anyone post a solution for such case?

  81. Moonman says:

    Great article but for the life of me I can’t figure out what TVData is?  I’ve read this article 160 times and can’t figure it out…

  82. Paul Robinson says:

    Sorry Moonman – not trying to confuse you!  TVData is the name of a dataset I created in the Visual Studio designer which has a single Presenters table containing ID, PresenterName and ProgrammeName columns (as in the above image).

  83. I was posting a WPF question on stackoverflow and I took a few minutes to tie up loose ends on a question

  84. hakan_740@hotmail.com says:

    Hi Powlo

    Its really a great post, :thumbs up:

    Im adopting your approach now in my site, however im facing a minor issue (i hope its minor).

    Lets say that i have two records in my dataset , each one has its own category (yet they are in the same dataset) , i bounded them to SPGrid , it worked fine , but i need to create a different actions in the menu for either.

    MyDataRecord1 >> Action is Delete

    MyDataRecord2 >> Action is Edite

    can i populate SPMeue items depending on the data??

    (i.e. can i build my own menu template ? )

    Thanks in Advance and Keep Up The Brilliant work.

  85. dewing1984 says:

    When I click on the SPField Item in the web part the ECB is not displayed ? I have a similar web part which seems to work all. Not sure why this one isnt working ?

    I am not even sure how to debug this.

                   #region CreateEmailECB

                   SPMenuField coleMail = new SPMenuField();

                   coleMail.HeaderText = "E-Mail";

                   coleMail.ImageUrlFormat = "/_layouts/images/EML16.GIF";

                   coleMail.ToolTipFields = "E-mail";

                   coleMail.MenuTemplateId = "contactECBMenu";

                   coleMail.NavigateUrlFields = "E-mail";

                   coleMail.NavigateUrlFormat = "mailto:{0}";

                   coleMail.TokenNameAndValueFields = "EMAIL=E-mail";

                   MenuTemplate emailECB = new MenuTemplate();

                   emailECB.ID = "contactECBMenu";

                   MenuItemTemplate EmailMenu = new MenuItemTemplate("Click to Email"/*, "/_layouts/images/EML16.GIF"*/);

                   EmailMenu.ClientOnClickNavigateUrl = "mailto:%EMAIL%";

                   MenuItemTemplate copyEmailToClipBoardMenu = new MenuItemTemplate("Copy to Clipboard"/*, "/_layouts/images/COPY.GIF"*/);

                   copyEmailToClipBoardMenu.ClientOnClickScript = "CopyToClipBoard(‘%EMAIL%’)";



                   coleMail.SortExpression = "E-Mail";



                   #endregion CreateEmailECB

  86. DarinBradford says:

    I’ve used this example and love it, thanks. Now I’m trying to take it to the next level. I want this webpart to be a provider webpart that another webpart could consume. so when a slection is made,another webpart could show the details. I’ve struggled with this for several days. I was wondering if anyone had an example of anything close. A SPGridview provider webpart??

    thanks in advance.

  87. Nice work!!

    Did you happen to know if I use the SPGridView, the columns do not display as a dropdown link with sorting options like asc/des and with some distinct values -what I can see in a usual SharePoint document library webpart column..? What exactly do I need to do for that?

  88. SharePoint has a little known web control called SPGridView. This control can give you a SharePoint list-like

  89. ramkrishnet@hotmail.com says:

    Amazing work Paul. Sorting, grouping worked for me like described. What I wanted is to display # of child elements for each group. e.g.

    Parent1 (3)<— Number of elements in a group.




    Parent2 (2)



    Any help is much appreciated.

  90. The out of the box Search Core Result web part displays search result in a format that is best suited

  91. GregJS says:

    Hi Powlo,

    Thanks for this great post. It was very helpful. I had something working in a very short amount of time.

    I’m having one problem still though, and I’m wondering if you might be able to give me some advice.

    I’m trying to use the technique described in this post to display task items from all the Task Lists in my whole site collection. I’m working on the links, and the problem I have is that for the NavigateURLFormat property, the url will be different depending on which task list the item is from. Providing an ID is not enough. I have to specify which Task List the item is from also.

    Do you know how I might be able to get the url for each task item as part of the query I do(using SPSiteDataQuery), and then incorporate that info into the NavigateURLFormat in such a way that it’s different for each item in the list? Or will I have to pass the url to some kind of redirector page?



  92. When i enable grouping and then sort the rows i get weird groups… and some times the first group doesnt get the (+) expand…anyone is having this problem?

  93. michael8 says:

    Hi everyone,

    I just started to use .Net and Sharepoint

    I just want to know if it is possible to apply the sorting of the data in the SPGridView on Pageload?

    If it is not, I need help to do the following:

    get data from a list using CAML query and then use it as Datasource for the SPGridView…

    Best Regards,


  94. itsaliakber says:

    Thanks a lot Paul for such an awesome article.

    I would like to know, when grouping if i just wanted to display only the column value nothing else, how will i get it. Though i had remove GroupDescriptionField & GroupFieldDisplayName. The Groupfield is being displayed.

    Thanks a million in advance

  95. srikanth.vadlakonda@live.com says:

    How to hide menu (dropdown menu) in some conditions? I was trying set MenuTemplate visible false. It is hiding entire column. I want show column without dropdown menu.

  96. srikanth.vadlakonda@live.com says:

    How to hide menu (dropdown menu) in some conditions? I was trying set MenuTemplate visible false. It is hiding entire column. I want show column without dropdown menu.

  97. LeonCapri says:

    Hi all,

    I have the same problem as kasper@nathansen.dk three years ago… I get the following error: "The type or namespace name 'TVData' could not be found ( are you missing a using directive or an assembly reference?)".

    What's wrong?

    Thanks for this post and your response 🙂

  98. saikatbiswas82 says:

    This is the thing I was looking for. Thanks a lot Paul.

  99. imagremlin says:

    I'm following this excellent article on how to take advantage of these classes. Got working most of what I need, but hit a snag.

    I'm adding menus to my items. The tokens are resolving OK, except that in one of my urls I have a repeated token. Like this:

    targetColumn.TokenNameAndValueFields = "HOSTURL=HostUrl,DOCID=DocumentId,LISTID=ListId";

    ModerateMenuItem.ClientOnClickNavigateUrl= %HOSTURL%/_layouts/… (a bunch of stuff) … &ListId={%LISTID%}&Source=%HOSTURL%&IsDlg=1

    The first %HOSTURL% is matched to the property on the data source, but the second is not. It renders as %HOSTURL%

    I tried adding a second HOSTURL entry on TokenNameAndValueFields I get an exception:

    System.ArgumentException – mscorlib

    Message: An item with the same key has already been added.

    Tried with another token name, say HOSTURL2=HostUrl. Same exception

    Any ideas?

  100. Excellent job. Exactly what we were looking for. Thanks for taking the time …

    Thanks for sharing. I have been article share for everybody about topic  


Comments are closed.

Skip to main content