.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

Create SPList grouped by a field in SPView

SharePoint 2007

Category SharePoint 2007  | Publication Date : 8/15/2009

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 sample:

private void CreateGroupByView(SPWeb web)
{
    SPList MyList= web.Lists["MyList"];
    string viewQuery = "<GroupBy Collapse=\"True\" GroupLimit=\"100\">";
    viewQuery += "<FieldRef Name=\"Title\" Ascending=\"True\"/>";
    viewQuery += "</GroupBy>";
    StringCollection viewFields = new StringCollection();
    viewFields.Add("MyView");
    MyList.Views.Add("Grouped By Title", viewFields, viewQuery, 100, true, true, SPViewCollection.SPViewType.Html, false);
}