Programing QA

Programing/Developing Questions & Answers. Focus on business application material

Dynamically create list, apply content type & add fields to view using client object model & C#

Create New List

Step 1: Create ClientContext using SharePoint Client Object Model:

Code Snippet
  1. Microsoft.SharePoint.Client.ClientContext context = new Microsoft.SharePoint.Client.ClientContext("http://myserver/mysite");
  2. context.Credentials = new System.Net.NetworkCredential("username", "password", "domain");

 

Step 2: Create the new SharePoint List by setting the initial parameters:

Code Snippet
  1. Microsoft.SharePoint.Client.ListCreationInformation info = new ListCreationInformation();
  2.  
  3. info.Description = "My List Description";
  4. info.Title = "My List Title";
  5. info.TemplateType = 101; // For creating document library
  6.  
  7. Microsoft.SharePoint.Client.List list = context.Web.Lists.Add(info);

 

Step 3: Before we perform the actual “Save” we can use the List object to setup more parameters:

Code Snippet
  1. list.EnableAttachments = true;
  2. list.ContentTypesEnabled = true;
  3.  
  4. list.Update();

 

Step 4: Like every time, this will perform the actual “Save”:

Code Snippet
  1. context.ExecuteQuery();

 

Final: We will probably want to id of the newly created list. that is the way to get it:

Code Snippet
  1. context.Load(list, l => l.Id);
  2.             context.ExecuteQuery();
  3.             Guid myNewListID = list.Id;

 

Apply content type to list:

Step 1: Getting the List we don’t already have it and apply the Content Type.

Code Snippet
  1. List list = context.Web.Lists.GetById(listid);
  2. ContentType ct = list.ContentTypes.GetById("0x34234234234357677212111");
  3. list.ContentTypes.AddExistingContentType(ct);
  4.  
  5. context.ExecuteQuery();

 

Add fields from the recently added content type to the default view :

Step 1: Get the DefaultView and add desired fields.

Code Snippet
  1. List list = context.Web.Lists.GetById(listid);
  2. View view = list.DefaultView;
  3. view.ViewFields.Add("MyCustomContentTypeColumn");
  4. view.Update();
  5.  
  6. context.ExecuteQuery();

 

Amir.