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"}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(); }}
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: