Reader Level:
Articles

Check if list exists using TryGetList method in SharePoint 2010

By Vijai Anand on March 25, 2011
In this article we will be seeing how to check if list exists using TryGetList method in SharePoint.
  • 0
  • 0
  • 41194

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

Vijai Anand

Vijai Anand has been working in IT industry for over 5 years. He holds Bachelor's degree in Electronics and Communication Engineering. Vijai write articles and blogs related to SharePoint 2013, SharePoint 2010, Silv... Read more

COMMENT USING

Trending up