Sunday, February 27, 2011

Add Content type to a list in share point (Show content types under new button drop down for a list)

In the list we have new option in the menu.By using that new button we will generate the new item. Recently i have a requirement that to add new content types to all the websites in the site. It will take lot of time to go through ui. Programatically it will become easy to update the all the lists in the web.
This is the code to add the list contents in share point lists
//add the content types to a list by that we can see it under the new button dropdown list
private static void AddContentTypesToList(SPWeb currentWeb)
{
    string listTitle = string.Empty;
    SPList currentList;
    List< SPContentType > contentTypes = new List< SPContentType >();
    contentTypes.Add(currentWeb.ContentTypes["Task"]);
    contentTypes.Add(currentWeb.ContentTypes["Message"]);
    Console.WriteLine("Enter the list title to add the content types");
    listTitle = Console.ReadLine();
    if (!string.IsNullOrEmpty(listTitle))
    {                
      currentList = currentWeb.Lists[listTitle];
      if (currentList != null)
      {
        for (int i = 0; i < contentTypes.Count; i++)
        {
          if (currentList.ContentTypes[contentTypes[i].Name] == null)
          {
            currentList.ContentTypes.Add(contentTypes[i]);
            currentList.Update();
            Console.WriteLine("content type " + (currentList.ContentTypes[contentTypes[i].Name]) + " Added");
          }
          else
          {
            Console.WriteLine("content type" + (currentList.ContentTypes[contentTypes[i].Name]) + "already added");
          }
         }
       }
       else
       {
         Console.WriteLine("list not exists in the current web");
       }
      }
      else
      {
        Console.WriteLine("list title not be empty or null");
      }
 }
 
In the above code we are adding the content types to the userdefined list., after that we are checking that the content types in the list exists or not. If it exists, it will do nothing. If not exists it adds the list that we want to add the content types. After updating the list the content types adds success fully. In the new button drop down we will get the content types we added to the list.

I think this will help you.

Share this