Check if list exists using TryGetList method in SharePoint 2010


In this article we will be seeing how to check if list exists using TryGetList method in SharePoint.

Normally we will be using SPList list = web.Lists[listName]; but it throws a null reference error if the list is not there. So we will be looping through the SPListItemCollection object and check if the list exists. In SharePoint 2010, a new method "TryGetList" is implemented to get the list and check if the list exists.

Using powershell script:

$siteURL="http://serverName:1111/"
$listName="Shared Documents"
$site=Get-SPSite $siteURL
$web=$site.RootWeb
$list=$web.Lists.TryGetList($listName)
if($list -ne $null)
{
  write-host -f green $listName "exists in the site"
}
else
{
  write-host -f yellow $listName "does not exist in the site"
}

TryGetList1.gif

Using C# code:

using (SPSite site = new SPSite("http://serverName:1111/"))
{
  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();
     }
}

TryGetList2.gif

Up Next
    Ebook Download
    View all
    Learn
    View all