Thursday, April 21, 2011


In this post we will discuss about SharePoint 2010 list and also we will some code sample of SharePoint 2010 object model.

Also you can check out:

- Steps to Create a list in SharePoint 2010

- Difference between site pages and application pages

- Difference between SharePoint-hosted, auto-hosted and Provider-hosted apps in SharePoint 2013

You can access a List by its name or by its URL.

- When retrieving a list by name, you can use the TryGetList method of the SPListCollection, which returns null if the list does not exist.

- When retrieving the list by the URL, you can use the GetList method of the SPWeb object, which throws a System.IO.FileNotFoundException if the list does not exist.

Code Samples:

using (SPSite siteCollection = new SPSite("Site URL"))
{
using (SPWeb site = siteCollection.OpenWeb)
{
SPList lstName = site.Lists.TryGetList("NameOfTheList");
if(lstName  != null)
//do your work
else
//List does not exists
try
{
SPList taskList = site.GetList("/Lists/Tasks");
//do your work
}
catch(FileNotFoundException)
{
//List does not work
}
}
}

- Lists maintain items in a Microsoft.SharePoint.SPListItemCollection object, which is accessible via the Items property of SPList.

- Items in the collection are returned as Microsoft.SharePoint.SPListItem objects.

- You can iterated over using a foreach statement, or directly accessed using either the item’s ID or index.
-->
- Each individual SPListItem maintains a Hashtable of values representing the properties of the item.

//Add new item to list
SPListItem newItem = list.Items.Add;
newItem["Title"] = "This will be the title";
newItem.Update;

//Bind the item to gridview
SPListItemCollection items = list.Items;
gridview1.DataSource = items;
gridview1.DataBind;

//Delete Item by Index
list.Items[0].Delete;

//Update Item by Index
SPListItem updateItem = list.Items[0];
updateItem["Title"] = "Updated Title";
updateItem.Update;

- When creating new items in a list, the Update method must be called to save the new item. If the Update method is not called, then the list item will be lost.

- If the item was edited by another user before the update is saved, the operation will fail.

0 Comments:

Post a Comment