Read a Sharepoint List using Object Model


In this article we will see how to read from a sharepoint list using sharepoint object model. 
  • To access the items of a sharepoint list first of all we need to connect to the Sharepoint Site or in other words we can say that we need to open that Sharepoint site and for this purpose we will use SPSite and SPWeb Objects. 
  • To access a List we will use SPList object.
  • To get all the list items from a list we will use SPlistItemCollection object.
  • To read the Item Collection obtained from SPlistItemCollection object we will use SPListItem object.
Let's see step by step how we can read List items from a List.

Step 0: Create a Sharepoint List named Products and Add two columns in it Product ID and Product Name as shown in the below figure.

1.gif
 
Add items in the list by clicking on New button.

Step 1: Open Visual Studio and create console application.

2.gif
 
Step 2: Add reference to Microsoft.Sharepoint.dll.

3.gif
 
Step 3: Create one SPSite object and pass site url as a parameter to it.

//SPSite object
SPSite oSpSite = new SPSite("http://spdevserver:1002/");

Step 4: Create SPWeb Object to open the Web.

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

Step 5: Create SPList object to access the List. Here we need to pass List Name which we want to access from Sharepoint site. If you know the ID than instead of name we can pass ID also.

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

Step 6: Create SPListItemCollection to get all the list items.

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

Step 7: Now we have all the list items in the itemcollection object. Iterate through each and every item in the ItemCollection object.

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

Output:

4.gif