Tags

, ,

I am not going to reinvent the wheel. Samples of code for removing a content type from a list can be found all over the internet. What I want to do is to present a way to organize the code and make it reusable. And with a little help from extension methods, this can be achieved very easy.

Before deleting the content type, I need to be sure it is attached to the list first, otherwise code will end up with an error. For this I have created the following extension method:

        /// <summary>
        /// Get content type id (SPList extension method)
        /// </summary>
        /// <param name="lst"></param>
        /// <param name="contentTypeName"></param>
        /// <returns></returns>
        public static Nullable<SPContentTypeId> GetContentTypeId(this SPList lst, string contentTypeName)
        {
            for (int i = 0; i < lst.ContentTypes.Count; i++)
            {
                if (lst.ContentTypes[i].Name == contentTypeName)
                {
                    return lst.ContentTypes[i].Id;
                }
            }
            return null;
        }

This methods is supposed to return an SPContentTypeId if content type with specified name is attached to the list, or null if not. For sure you can avoid iteration, but I prefer it because it might be possible to adapt the code later for identifying the content type by other properties convertible to string.

The second method is based on the first one and is deleting the content type if it is attached to the list. Again, iteration is not the representing the optimized code, but is easy for me to change this way.

        /// <summary>
        /// Remove content type (SPList extension method)
        /// </summary>
        /// <param name="lst"></param>
        /// <param name="contentTypeName"></param>
        public static void RemoveContentType(this SPList lst, string contentTypeName)
        {
            Nullable<SPContentTypeId> cTypeId = lst.GetContentTypeId(contentTypeName);
            if (cTypeId != null)
            {
                lst.ContentTypes.Delete((SPContentTypeId)cTypeId);
                lst.Update();
            }
        }

Assuming you have a variable(SPList type) called “mylist”, code to delete the content type become simple:

mylist.RemoveContentType("Content type name");
Advertisements