Wednesday 30 January 2013

Adding Items to 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 AddItemsToList
{
    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;

            //Getting List
            List list = site.Lists.GetByTitle("Students");

            //Adding Items to List
            ListItemCreationInformation listItemCreationInformation = new ListItemCreationInformation();

            ListItem listItem = list.AddItem(listItemCreationInformation);
            listItem["Title"] = "1";
            listItem["First Name"] = "John";
            listItem["Last Name"] = "Abraham";
            listItem["Age"] = 35;
            listItem.Update();

            listItem = list.AddItem(listItemCreationInformation);
            listItem["Title"] = "2";
            listItem["First Name"] = "Sharukh";
            listItem["Last Name"] = "Khan";
            listItem["Age"] = 40;
            listItem.Update();

            clientContext.ExecuteQuery();
            Console.WriteLine("Items Added Successfully To List");
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment