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 (6)

  1. Vin Diesel Pham says:

    Programmatically retrieve the items in a list based on the current user : EasyCoded

  2. Dave says:

    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.

  3. sowmyancs says:

    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.

  4. sowmyancs says:

    Fantastic. Yes using that method we can retrieve the lists. Thanks Dave !