Skip to content

Web Parts: Using Filtered Data with SPList

July 22, 2010

This may be common knowledge, but up until recently I only knew how to retrieve the entire contents of a list with SPList, sorted by Sharepoint’s default settings with no filter. There’s an easy way to tailor the returned data to your liking, however. First, create a view that has the filter and sort options  you want. This is important though: make sure that all three of the key fields (Title, Event, etc.) are displayed in your view. Tick the boxes next to, for example, Title (linked to item with edit menu), Title (linked to item), and Title. Otherwise, the Web Part will throw an exception if you attempt to display that field’s contents. This view shouldn’t be one that people will ever see; it’s just for your Web Part to use. Now, simply use the following code to only retrieve items included in and sorted by that view.

SPList list = web.Lists[listName];
SPView view = list.Views[viewName];
SPListItemCollection collection = list.GetItems(view);

foreach (SPListItem item in collection)
{
    // Loop code
}

That’s all there is to it! Another thing, though. You may have noticed in previous posts that I would loop through items like this:

foreach (SPListItem item in list.items) { ... }

I also recently learned that doing that means Sharepoint will make a database call every iteration through the loop. That’s horribly inefficient. By loading the entire returned list into my variable collections, only a single query is executed and the server load is greatly reduced.

Resources I Used:

Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: