Online Training On SharePoint

Tuesday, 3 March 2009

Hiding/Displaying Content Type with SharePoint Object Model

I had a document library with which multiple content types are associated. When a user click the New button in the document library, I need to show or hide these content types based on the number of documents associated with a particular content type.When a specified number of documents are uploaded for a specific content type user should not be able to see this content type under the new button and when some documents associated to this content type, are deleted the content type should start appearing under the New menu item.

We can achieve this with the help of SharePoint Object Model. First we will find the number of documents for any specific content type in the document library and then in ItemUpdated event and ItemDeleted Events for the document library we can have the code to hide/display the Content Type:

To calculate the number of items related to a specific Content Type in a document library we can use following Code (cant put the code so putting it in sky drive):

private int FindNumberOfItems(SPList list)
SPQuery qry = new SPQuery();
qry.Query = "<Where><Eq><FieldRef Name='ContentType' /><Value Type='Text'>ContentTypeName</Value></Eq></Where>";
return list.GetItems(qry).GetDataTable().rows.count;

Download the code from:

So lets say X is the Number of Docs associated to a particular content type returned by the above code and now we want to hide the content Type when this number reaches 5 then the code required to be used is:

Code in the ItemUpdated Event:
If (X>=5)
properties.List.ContentTypes["NameOfContentType"].Hidden = true;
//This will make the Content Type not visible under “New” button in the toolbar

Now same way we can start displaying this content type once the number of docs reaches below the specified limit. We need to call the code in the ItemDeleted Event.

Code in the ItemDeleted Event:
If (X<5) properties.List.ContentTypes["NameOfContentType"].Hidden = false; //This will make the Content Type visible under “New” button in the toolbar

You may be interested to see
Introduction to Content Types

Post a Comment
Related Posts with Thumbnails