I recently had to create a custom web part that could consistently display list items in a consistent manner, and it had to allow the user to point it at any list with any filtering and sorting criteria. Rather than build my own filtering and sorting funcitonality, I found it easier, more user-friendly, and more flexible to leverage SharePoint’s list Views.
The idea is simple – let the users create a view, complete with sorting and filtering rules, and then use that as the basis for selecting the items to display. The SharePoint object model makes this easy.
The key is building an SPQuery object from an SPView object:
using (SPWeb rootWeb = SPContext.Current.Site.RootWeb)
{
//get list view
SPList theList = rootWeb.Lists[_listName];
SPView theView = theList.Views[_viewName];
//get the query, based on the view
SPQuery theQuery = new SPQuery(theView);
//run the query, get the items collection
SPListItemCollection viewItems = theList.GetItems(theQuery);
//build a display for the items in the collection
…
}