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 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 "https://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()

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world 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

    Reply
  • 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

    Reply
  • 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

    Reply

Leave a Reply

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