Sunday 15 September 2013

Check if list exists using TryGetList method in SharePoint 2010


Now lets see how to check if list exists using TryGetList method in SharePoint.

Normally we will be using 

SPList list = web.Lists[listName]; 

to get a list.

But, it throws a null reference error if the list is not there(i.e., in case if it is being deleted from the site using browser). So we will be looping through the SPListItemCollection object and check if the list exists or would go for exception. In SharePoint 2010, a new method "TryGetList" is implemented to get the list and check if the list exists. Lets see how the code works out.


using (SPSite site = new SPSite("http://serverName:1234/"))
{
  using (SPWeb web = site.RootWeb)
     {
        SPList list = web.Lists.TryGetList("My List");
        if (list != null)
        {
          Console.WriteLine("List exists in the site");
        }
        else        

        {
          Console.WriteLine("List does not exist in the site");
        }
          Console.ReadLine();
     }
}

2 comments:

  1. I do know share point, but i appreciate your interest to share the coding with others.

    ReplyDelete