Export (0) Print
Expand All

SPContentTypeCollection.Add Method

Windows SharePoint Services 3

Adds the specified content type to the collection.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

public SPContentType Add(
	SPContentType contentType
)

Parameters

contentType
Type: Microsoft.SharePoint.SPContentType
An SPContentType object to add to the collection.

ExceptionCondition
SPException

The name of the content type is either an empty string or is already in use by another content type in the collection.

The following example shows a console application that gets a content type from the collection that is returned by the AvailableContentTypes property. It then adds that content type to the collection that is returned by the ContentTypes property of an SPList object.

using System;
using Microsoft.SharePoint;

namespace Test
{
   class ConsoleApp
   {
      static void Main(string[] args)
      {
         using (SPSite site = new SPSite("http://localhost"))
         {
            using (SPWeb web = site.OpenWeb())
            {
               // Get a content type.
               SPContentType ct = web.AvailableContentTypes[SPBuiltInContentTypeId.Document];

               if (ct != null) // We have a content type
               {
                  try // Get a list.
                  {
                     SPList list = web.Lists["Test List"]; // Throws exception if does not exist

                     // Make sure you can add content types.
                     list.ContentTypesEnabled = true;

                     // Add the content type to the list.
                     if (!list.IsContentTypeAllowed(ct))
                        Console.WriteLine("The {0} content type is not allowed on the {1} list",
                                           ct.Name, list.Title);
                     else if (list.ContentTypes[ct.Name] != null)
                        Console.WriteLine("The content type name {0} is already in use on the {1} list",
                                           ct.Name, list.Title);
                     else
                        list.ContentTypes.Add(ct);
                  }
                  catch (ArgumentException ex) // No list is found.
                  {
                     Console.WriteLine("The list does not exist.");
                  }
               }
               else // No content type is found.
               {
                  Console.WriteLine("The content type is not available in this site.");
               }
            }
         }
         Console.Write("\nPress ENTER to continue...");
         Console.ReadLine();
      }
   }
}

Community Additions

ADD
Show:
© 2015 Microsoft