Thursday, November 20, 2008

Filter SharePoint List items based on User context

Filtering the items created by the logged in user can be done by simply modifying the existing View or by adding a new view which has "Created By" value = [Me].

But how to achieve the same thing in Code, Getting a list looping it and filtering the result will do. But sure performance will go down.

Here comes the CAML query for the rescue of SharePoint developer. CAML is having a token which automatically uses the current user context.

So we can write a code snippet as follows to get items created by the current user.



SPList sList=[Get the list to query here];
SPQuery query = new SPQuery();
query.Query = string.Format(
"[Where]"+
+ "[Eq]"
+ "[FieldRef Name='Author' LookupID='TRUE'/]"
+ "[Value Type='User'][UserID /][/Value]"
+ "[/Eq]"
+ "[/Where]");
SPListItemCollection listItems = sList.GetItems(query);


you will get the list items only created by the current user, no iteration, no filteration happens only clean CAML query.

Replace all square brackets[ ] with angle brackets < >. Blogger refused to accept the angle brackets.

Happy coding,

1 comment:

Blog do henrique said...

thanks, very simple and work fine. good job.