Share via


How to filter a SharePoint List based on the Log In user’s properties (E.g. Department, etc.)

The best part of the problem was that the customer wanted to restrict (And not filter) the user to see only the items that are relevant to him. So you can’t use the normal way, where you would go to the list’s settings and filter the list on the columns asked for.

So we want a solution which is:-

a) Easy and efficient to implement

b) Should run every time and everywhere the list is visible.

c) Should run in the background, so that we don’t have to write the code in each of the pages

d) Should be applicable to all views.

e) It should be extensible for future additions.

The only solution which would implement all these points would be to create a dll (which has the custom code to filter the list), add this dll reference to a user control and then refer this control in a custom master page (which is a copy of the current master page).

For reference of how to implement the solution, following are the points:

1.  Create a custom Form library which has the Department field as “Department”. Create a class library project. Add references to the Microsoft.Sharepoint and System.Web dlls.

     As I got a lot of request for sharing the code for filtering the lists, I am sharing the same:

    1:  using System;
    2:  using System.Collections.Generic;
    3:  using System.Text;
    4:  using Microsoft.SharePoint;
    5:  using System.Web.UI;
    6:   
    7:  namespace WebPartLogic
    8:  {
    9:      public class WebPartLogic : System.Web.UI.UserControl
   10:      {
   11:          protected override void OnLoad(EventArgs e)
   12:          {
   13:              //Check whether it is the lists page or not.
   14:              // This step is optionally added to ensure 
   15:              // this code is not executed for all pages
   16:              if (System.Web.HttpContext.Current.Request.Url.Segments[1]
                     .ToString() == "FormList/")
   17:              {
   18:                  SPWeb web = SPContext.Current.Web;
   19:                  web.AllowUnsafeUpdates = true;
   20:   
   21:                  // For Library Name
   22:                  SPList _list = web.Lists["FormList"];
   23:                  string query = "";
   24:   
   25:                  query = "<Where><Eq><FieldRef Name=\"Department\" />                       <Value Type=\"Text\">"+ GetDepartment() + "</Value>                        </Eq></Where>";
   26:                  //query = ""; 
   27:                  //Update user views
   28:                  SPViewCollection viewColl = _list.Views;
   29:                  for (int i = 0; i < viewColl.Count; i++)
   30:                  {
   31:                      SPView view = viewColl[i];
   32:                      view.Query = query;
   33:                      view.Update();
   34:                  }
   35:   
   36:              }
   37:          }
   38:   
   39:          private string GetDepartment()
   40:          {
   41:              SPWeb web = SPContext.Current.Web;
   42:              string strDept = " ";
   43:              try
   44:              {
   45:                  SPList _list = web.Lists["User Information List"];
   46:                  SPUser user = web.CurrentUser;
   47:                  string quer = "<Where><Eq><FieldRef Name=\"Name\" />                       <Value Type=\"Text\">" + user.ToString() + "                       </Value></Eq></Where>";
   48:                  SPQuery query = new SPQuery();
   49:                  query.Query = quer;
   50:                  SPListItemCollection itemColl = _list.GetItems(query);
   51:                  strDept = itemColl[0]["Department"].ToString();
   52:              }
   53:              catch
   54:              {
   55:              }
   56:              return strDept;
   57:          }
   58:   
   59:   
   60:      }
   61:  }

2. In the class inherit the class – System.Web.UI.UserControl

3. Implement the method onLoad and copy the code I have sent you from the class.

4. Add strong name to the class library.

5. Now build the project. Drag and drop the WebPartLogic.dll into the GAC folder.

6. Do an iisreset.

7. Go to the SharePoint’s ControlTemplates folder. Create a custom user control. For that, you can go to the following location C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES and copy any of the existing user control and rename it - say NewWelcome.ascx. Now, remove all the content from the renamed user control and add only the directive that I given below.

<%@ Control Language="C#" Inherits="WebPartLogic.WebPartLogic,WebPartLogic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6c9c8cc0568cc97f" compilationMode="Always" %>

8. Or you could use the user controI have sent you .

9. Now our user control is ready to execute our code implemented to hide to the webparts at the time of page load. Our next step is to add this user control in our custom master page and apply that master page to our SharePoint site. If you are using default.master as your master page then follow the below steps to create a custom master page.

a. Make a copy of default.master page by taking it from the following location C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL.

b. Rename it, say mydefault.master, and open it for editing.

c. Register and create a control tag of our user control using the below tags.

    <%@ Register TagPrefix="wssuc" TagName="HideWebPartControl" src="~/_controltemplates/HideWebPartControl.ascx" %>

And the following tag after the form tag.

    <wssuc:CiscoControl id="CiscoControl" runat="server" EnableViewState="false"></wssuc:CiscoControl>

10. Now we are ready with our custom master page with the functionality hide all the ListViewWebParts in all SharePoint pages. Our next step is to apply this custom master page to the SharePoint site. To do that follow the below steps.

a. Open the SharePoint site, and navigate to the Master Page Gallery - Site Actions à Site Settings à Galleries à Master Pages

b.  Upload the custom master page to this gallery

c. Now apply the master page to the site by going to the following location - Site Actions à Site Settings à Look and Feel à Master Page

 

Summarizing, advantages of this solution:

1. Very clean and efficient

2. Extremely extensible as you can add any custom code to filter the list.

3. Filters the List automatically and serves the requirement transparently.

Comments

  • Anonymous
    June 24, 2008
    PingBack from http://stevepietrek.com/2008/06/24/links-6242008/

  • Anonymous
    July 01, 2008
    Bill Gates Tribute Video: Looking Back, Moving ahead ( Part 1 , Part 2 ) OT: Time to Relax Sudoku Addin

  • Anonymous
    August 21, 2008
    The idea looks good. Can you provide the code you mentioned? Or please provide some pointers. I checked out the SPList class and I didnt see any set filter methods. So I was really wondering how is that going to work? Thx, Srinivas

  • Anonymous
    September 03, 2008
    Can you please provide source code you mentioned.

  • Anonymous
    September 03, 2008
    I have attached the code. Please check the code above.

  • Anonymous
    January 14, 2010
    Hi, I have just started to maintain the sharepoint intranet site in my company.  I am an old style programmer and is trying to move to do some web development work.  I got an assignment to filter the content of the announcement list based on the company attribute of the user in the active directory.  I did a lot of search in the web.  I finally found this blog and tried to create the custom web part and followed the instruction to put it in the default master page.  In the end I can update the query of the view.  However I have to manually refresh the page to bring the change on the browser.  Do you have a better way to refresh the list? Thanks Paul PS. My company is using sharepoint service 3.0.

  • Anonymous
    February 16, 2010
    This seems to be wonderful. I just have the exact requirement. But we are implementing on WSS 3.0 and no MOSS. Will i be able to implement the same for WSS 3.0.. Thanks you very much in advance. Jagadish

  • Anonymous
    September 07, 2010
    Hi there, will you be able to package this as a solution that can be deployed

  • Anonymous
    September 12, 2010
    what is this CiscoControl?? and where is the source code? thanks

  • Anonymous
    January 16, 2011
    Hi Varun, Greetings! I am Deepthi from Han Digital Solution (P)Ltd. happened to see your profile in Naukri.I would like to share an opportunity on Sharepoint/MOSS req. with my CMM Level 5 client so,in case you are interested pls do write/reach me deepthi@handigital.com/040–40493882. Awaiting for reply. Regards, Deepthi

  • Anonymous
    January 29, 2012
    I did every step but list still loads with all (not filtered ) data