Code Snippet – Programmatically Configure the Order By and Group By Properties of the SharePoint Lists and Document Libraries Views

If you want to set the Order By or Group By properties for the given list or document library views programmatically, you have to set the SPView Object’s Query property.


class Program
{
    static void Main(string[] args)
    {
        SPSite spSite = new SPSite("http://sp2010vm/");
        foreach (SPWeb spWeb in spSite.AllWebs)
        {
            spWeb.AllowUnsafeUpdates = true;

            SPListCollection lists = spWeb.Lists;
            for (int i = 0; i < lists.Count; i++)
            {
                if (lists[i] is SPDocumentLibrary)
                {
                    if (((SPDocumentLibrary)lists[i]).IsCatalog == false)
                    {
                        SPDocumentLibrary spList = (SPDocumentLibrary)lists[i];
                        if (spList.Title == "Classified Documents")
                        {

                            //Update the View
                            SPView view = spList.Views["All Documents"];

                           ////Reset the View
                           //string viewQuery = @" <OrderBy><FieldRef Name=""FileLeafRef"" /></OrderBy>> "; 

                          //Set the Group By Properties
                          string viewQuery = @" <GroupBy Collapse=""TRUE"" GroupLimit=""100""> <FieldRef Name=""Classified_x0020_Document_x0020_Type"" Ascending=""True""/> </GroupBy> <OrderBy> <FieldRef Name=""FileLeafRef"" /></OrderBy>";
                               
                            view.Query = viewQuery;
                            view.Update();
                            spList.Update();
                        }
                    }
                }
            }

            spWeb.AllowUnsafeUpdates = false;
            spWeb.Dispose();                  
        }

        spSite.Dispose();
    }
}

Tip: To find the syntax for the CAML Query order by and group by settings, you can download and use the free tool SharePoint Manager 2010 available on the codeplex. On the development machine, Set the group by settings in the browser interface for the views and visit the SharePoint Manager to find the syntax for the group by and order by CAML.

Advertisements
This entry was posted in SP2010 Code Snippets. Bookmark the permalink.