Programmatically retrieve the items in a list based on the current user
We can accomplish this requirement by using SPQuery. This sample code I have developed for taking all the items with modified by (column name is "Editor") user BLR3R7-19C\\test1.If you are using this code in a SharePoint web context then oWeb.CurerntUser will return the current login user details.
1: SPList oList = oWeb.Lists["Shared Documents"];
2: SPUser oUser = oWeb.AllUsers["BLR3R7-19C\\test1"];// replace it by oWeb.CurrentUser.Name
3: string strquey = oList.DefaultView.Query;
4: SPQuery query = new SPQuery();
5: query.Query = "<Where><Eq><FieldRef Name=\"Editor\" /><Value Type=\"User\">" + oUser.Name + "</Value></Eq></Where>";
6: SPListItemCollection results = oList.GetItems(query);
7: Console.WriteLine("Result Count: " + results.Count);
One Tip: a simple method to construct CAML queries would be create a view in OOB with all the parameters to filter. Then access it in the code and take the query property of that view which will return the CAML query and after that you can delete it out J !
1: SPView oView = oList.Views["TestView"];
2: string strView = oView.Query;
Comments
Anonymous
October 01, 2008
PingBack from http://www.easycoded.com/programmatically-retrieve-the-items-in-a-list-based-on-the-current-user/Anonymous
October 01, 2008
Programmatically retrieve the items in a list based on the current user : EasyCodedAnonymous
October 08, 2008
Is there a way you can pull a list based on the users rights? I dont want to pull the whole list and check each list item to see if the current user has rights. Im hoping there is a way to pull the filtered list.Anonymous
October 08, 2008
I am sorry Dave. Per my knowledge there is no a way to pull the lists based upon user rights. Let me know if you get any workaround.Anonymous
October 09, 2008
Ok I found a way to do it using impersonation. Check out this article http://www.sharepointblogs.com/tanujashares/archive/2007/08/07/impersonation-in-sharepoint-2007.aspxAnonymous
October 09, 2008
Fantastic. Yes using that method we can retrieve the lists. Thanks Dave !