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.
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()
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
Send me your code for review!