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;

//Update the List

U2U doesn’t offer Group by in its UI, However you can use:
<GroupBy Collapse=”TRUE”><FieldRef Name=”Country” /></GroupBy> 
to the Query to get the Group by applied.

PowerShell to Set View Sort, Group By Options:

$web=Get-SPWeb -identity ""
$view =  $list.DefaultView  # To fetch a particular view, use:  $list.Views | ?{$_.title -eq "View-Name"}
$view.Query = '<OrderBy><FieldRef Name="Modified" Ascending="False" /></OrderBy>'

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

4 thoughts on “Set Sorting, Filter, Group By in SharePoint Views Programmatically

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

  • 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

  • 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


Leave a Reply

Your email address will not be published. Required fields are marked *