Wednesday 30 January 2013

Creating List in SharePoint 2010 using Client Object Model (C#)



Step 1: Create New Project. (Minimum .NET Framework 3.5)
Step 2: Add “Microsoft.SharePoint.Client” and “Microsoft.SharePoint.Client.Runtime” namespaces.
Step 3: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// SharePoint namespace
using Microsoft.SharePoint.Client;

namespace ListCreation
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://sharepointserver.com/";
            ClientContext clientContext = new ClientContext(siteUrl);
            clientContext.Credentials = new System.Net.NetworkCredential("admin", "password", "sharepointserver.com");
            Web site = clientContext.Web;

            //Creating List
            ListCreationInformation listCreationInformation = new ListCreationInformation();
            listCreationInformation.Title = "Students";
            listCreationInformation.TemplateType = (int)ListTemplateType.GenericList;
            List list = site.Lists.Add(listCreationInformation);

            //Creating Columns
            Field firstNameField = list.Fields.AddFieldAsXml(
                @"<Field Type='Text'
                         DisplayName='First Name' />", true, AddFieldOptions.DefaultValue);

            Field lastNameField = list.Fields.AddFieldAsXml(
                @"<Field Type='Text'
                         DisplayName='Last Name' />", true, AddFieldOptions.DefaultValue);

            Field ageField = list.Fields.AddFieldAsXml(
                @"<Field Type='Number'
                         DisplayName='Age' />", true, AddFieldOptions.DefaultValue);

            clientContext.ExecuteQuery();
            Console.WriteLine("List Created Successfully");
            Console.ReadLine();
        }
    }
}


No comments:

Post a Comment