Wednesday 27 July 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.

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://chandanbadajena.blogspot.com/sites/mysite/Lists/ChandanKumarr";
GetListData(listUrl);

No comments:

Post a Comment