Wednesday, July 4, 2012

Set Sorting, Filter, Group By in SharePoint Views Programmatically

SharePoint List views uses CAML internally to Filter, Sort list items. In a Recent project, we had to programmatically set the Filter and Sort order of default views.

How to Get the CAML?
Simple! use U2U CAML Query builder, one of my favorite SharePoint tool.
Set Sorting, Filter, Group By in SharePoint Views Programmatically

C# code to set the View Filter, Sort options:
 //Get the List, say "Project Tasks" 
  SPList ProjectTasks = web.Lists["Project Tasks"];

 //Get the view 
 SPView ProjectTasksView = ProjectTasks.DefaultView;
 // Or you can get a specific view by: List.Views["View-Name"]

 //Set the CAML Query
 string viewQuery = @" <Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>In Progress</Value></Eq></Where><OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy> ";
 //Update the view 
  ProjectTasksView.Query = viewQuery;
  ProjectTasksView.Update();

  //Update the List
  ProjectTasks.Update();

U2U doesn't offer Group by in its UI, However just append <GroupBy Collapse="TRUE"><FieldRef Name="Country" /></GroupBy>  to the Query to get the Group by applied.

PowerShell way to Set View Options:
$web=Get-SPWeb -identity "http://sharepoint.com"
$list=$web.lists["Tasks"]
$view =  $list.DefaultView  # To fetch a particular view, use:  $list.Views | ?{$_.title -eq "View-Name"}
$view.Query = '<OrderBy><FieldRef Name="Modified" Ascending="False" /></OrderBy>'
$view.Update()
$list.Update()



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

4 comments :

  1. Hi Salaudeen
    I have tried your codesnippet in c#, but
    my list doesn't update - inside the list the filter is set correctly - on screen the data is unchanged. Can you help me - cioa juergen

    ReplyDelete
  2. Hi Salaudeen,
    I was able to set sorting and filering,however the View's Title dropdown still shows all the items from the defaul view, available for sorting and filtering. Is there a way to show updated items in this dropdown.
    - Neeraj

    ReplyDelete
  3. i want to create a view for multi level lookup in sharepoint designer 2013. can u please help me

    ReplyDelete

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...