top of page
Writer's pictureVijai Anand Ramalingam

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:

  1. $siteURL="http://serverName:1111/"

  2. $listName="Shared Documents"

  3. $site=Get-SPSite $siteURL

  4. $web=$site.RootWeb

  5. $list=$web.Lists.TryGetList($listName)

  6. if($list -ne $null)

  7. {

  8. write-host -f green $listName "exists in the site"

  9. }

  10. else

  11. {

  12. write-host -f yellow $listName "does not exist in the site"

  13. }

📷

Using C# code:

  1. using (SPSite site = new SPSite("http://serverName:1111/"))

  2. {

  3. using (SPWeb web = site.RootWeb)    

  4. {       

  5. SPList list = web.Lists.TryGetList("My List");

  6. if (list != null)       

  7.  {         

  8. Console.WriteLine("List exists in the site");        

  9. }

  10. else        

  11. {         

  12. Console.WriteLine("List does not exist in the site");        

  13. }         

  14. Console.ReadLine();     

  15. }

  16. }


0 comments

Kommentarer


bottom of page