Prash's Blog

Create SPList grouped by a field in SPView November 13, 2009

Filed under: SharePoint — prazjain @ 3:06 pm
Tags: ,

Here I do a groupby on SPList so that it can be viewed in TreeView UI with collapsible groups.

Step through of code:

  1. Get the reference to SPList
  2. Define a CAML query to group the list by “Title” of the SPListItem. More than one field can be added by adding as many <FieldRef ../> tags inside the same GroupBy Tag.
  3. Add the fields you would want to see in the view, and set the view as default view for the list.

Code snippet:


/// <summary>

/// Creates a new default view for the history list. This default view is grouped by title of the list.

/// </summary>

/// <param name="web"></param>

private void SetupGroupByView(SPWeb web)

{

SPList historyList = web.Lists["History"];

string viewQuery = @"

<GroupBy Collapse=""True"" GroupLimit=""100"">

<FieldRef Name=""Title"" Ascending=""True""/>

</GroupBy>";

StringCollection viewFields = new StringCollection();

viewFields.Add("Information");

historyList.Views.Add("Grouped By Title", viewFields, viewQuery, 100, true, true, SPViewCollection.SPViewType.Html, false);

}

Advertisements
 

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