Friday, November 15, 2013

Create a list in SharePoint and Read List details using C#

Prepare the custom list with the name as Products and click Create to create a list as shown in the below figure:

   After creating a list you can add items in a list by selecting Add new item option.But before inserting items add columns in a list. You can add columns in a list by selecting Create Column option. Here I am adding two columns i.e. Product ID and Product Name.
     After adding the columns add rows in a list by inserting item.


Add as much as products you want just by clicking add new item

Now open visual studio and take a console application
Then write the below code in the Program.cs file.

Don't forget to add reference to Microsoft.SharePoint.dll


using System;
using System.Text;
using Microsoft.SharePoint;

namespace ReadSharePointList
{
    class Program
    {
        static void Main(string[] args)
        {
            //SPSite object
            SPSite oSpSite = new SPSite("http://mysite/");

            //Connect to the web using SPWeb object
            SPWeb oSPWeb = oSpSite.OpenWeb();

            //List Object to get the list from a sharepoint site
            SPList oSpList = oSPWeb.Lists["Products"];

            //Item Collection Object getting all the items form the list
            SPListItemCollection oSpListCln = oSpList.Items;

            //iterate through all the items in itemcollection object
            foreach (SPListItem item in oSpListCln)
            {
                Console.Write(item["Product ID"] + "\t\t");
                Console.WriteLine(item["Product Name"] + "\n");
            }
        }
    }
}


save and Run.

Note: If there is error in compilation change the platform target to X64 in the project properties.





0 comments:

Post a Comment