Monday 8 June 2015

Add a field to a SharePoint list using Client Side Object Model

This example adds a field to a SharePoint list. add an alias to the using statement for Microsoft.SharePoint.Client namespace so you can refer to its classes unambiguously. For example, using SP = Microsoft.SharePoint.Client;.

The example uses context.CastTo to do a cast. Before executing the query, the client library does not know the real type of the returned object "field" and SharePoint.Field is the only possible type. If you know the real type, you can use the ClientContext.CastTo<RealType> method to cast the object.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

SP.List list = context.Web.Lists.GetByTitle("Announcements"); 

SP.Field field = list.Fields.AddFieldAsXml("", 
                                           true, 
                                           AddFieldOptions.DefaultValue); 
SP.FieldNumber fldNumber = context.CastTo(field); 
fldNumber.MaximumValue = 100; 
fldNumber.MinimumValue = 35; 
fldNumber.Update(); 

context.ExecuteQuery();

No comments: