Delete content types in share point list (Remove the options under the new button dropdown in share point list)

In my previous post i was published how to add the content types to a list in share point. It is also possible to delete the content types in the share point lists. The following code deletes the required content types in the list.

//delete content types from a list
private static void DeleteContentType(SPWeb currentWeb)
{
  string listTitle = string.Empty;
  SPList currentList;
  List< SPContentType > contentTypes = new List< SPContentType >();
  contentTypes.Add(currentWeb.ContentTypes["Message"]);
  Console.WriteLine("Enter the list title to delete 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.Delete(currentList.ContentTypes[contentTypes[i].Name].Id);
          currentList.Update();
          Console.WriteLine("content type Deleted");
        }
        else
        {
          Console.WriteLine("content type" + (currentList.ContentTypes[contentTypes[i].Name]) + "not exists");
        }
      }
    }
    else
    {
      Console.WriteLine("list not exists in the current web");
    }
  }
  else
  {
    Console.WriteLine("list title not be empty or null");  
  }
}
As shown in the code i took a user defined list as SPContentType and i added the content types to the list which i want to delete, then loop the entire list items, if the content type exists in the list, then the content type will be deleted. If not exists do nothing.

Comments