Second Life of a Hungarian SharePoint Geek

December 5, 2009

Creating view to display list items created in the current month

Filed under: CAML, SharePoint — Tags: , — Peter Holpar @ 00:50

The task sounds rather simple at first: we should create a view that filters the items and displays only the ones that were created in the current month.

Unfortunately, the user interface gives only a very limited support to create views, so this task could be only implemented by creating two computed columns, first one for the first day of the month the item was created, and the second one for the last day. Then we could use these columns to compare with the current date (Today), when creating the view. I don’t like this solution, especially because of the need for the computed columns.

Instead of this, it is worth to create the view from code, for example, by cloning an existing view (like „All Items”), then by setting the Query property of the SPView class. Here we need a CAML query that makes it possible to filter for date intervals. That is exactly what DateRangesOverlap does. Since in this case the beginning and end dates are the same value, the value of the Created field, it must be included twice in the query.

Let’s see the final result:

SPView view = list.Views["All Items"].Clone("Current Month", 0, false, 
false);
view.Query = @"<Where><DateRangesOverlap><FieldRef
Name='Created' /><FieldRef Name='Created' /><Value
Type='DateTime'><Month
/></Value></DateRangesOverlap></Where>"
;
view.Update();

Nothing is perfect. DateRangesOverlap has a little issue when filtering for a given month. You can read about that in my former post: Using Month element in DateRangesOverlap can return items not in the specified month.

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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

Blog at WordPress.com.

%d bloggers like this: