Sunday, February 13, 2011

Get list data using SharePoint Object Model

Get list data using SharePoint Object Model:

This article explains how you can use the SharePoint Object Model(MOSS 2007) classes like SPSite and SPWeb in C# or Visual Basic code to fetch data from a custom SharePoint list.

This article explains how you can use the SharePoint Object Model(MOSS 2007) classes like SPSite and SPWeb in C# or Visual Basic code to fetch data from a custom SharePoint list.

Problem:
You want to get data on the basis of url (including siteurl+listname) from the custom SharePoint list.

Resolution:
In this scenario, we can use SharePoint Object Model classes to access data from custom SharePoint list.

public static bool CheckListExists(string listName, SPWeb web,ref SPList list)
{
try
{
//---Check list exist or not
if (web.Lists[listName]!=null)
{
list = web.Lists[listName];
return true;
}
return false;
}
catch (ArgumentException ex)
{
return false;
}
catch (Exception ex)
{
return false;

}
}



Above function used to check list exist in the SharePoint site or not.


public static void GetListData(string listUrl)
{
SPList objList = null;
char [] chrSplitter={'/'};
try
{
listUrl = listUrl.TrimEnd(chrSplitter);
string[] arrList = listUrl.Split(chrSplitter);
if (arrList != null && arrList.Length > 0)
{

using (SPSite site = new SPSite(listUrl))
{
using (SPWeb web = site.OpenWeb())
{
if(CheckListExists(SPEncode.UrlDecodeAsUrl(arrList[arrList.Length - 1]),web,ref objList))
{
//Add business logic here
}
}
}
}


}
catch (Exception ex)
{

}
}



Above function used to get data from SharePoint site by passing the url only. The url contain both site url and list name. For example:

From presentation layer, we make a call to GetListData function

string listUrl="http://amitkumarmca04.blogspot.com/sites/mcapassion/Lists/AmitKumar";
GetListData(listUrl);

Share:

0 comments:

About Me

My photo
Based in Bangalore, INDIA, Amit is a MCC. He has an MCA from the U.P.T.U., INDIA and holds Microsoft certifications including SharePoint 2007/2010/2013. He is an contributor to MSDN and http://amitkumarmca04.blogspot.com/. Amit have experience in SharePoint,ASP.Net with C#, Classic ASP, VB,Macros,HTML,JavaScript,JSON,BootStrap and AngularJS.

Followers

Labels