Checking to see if a list exists in SharePoint 2010

Posted Tuesday, October 20, 2009 3:17 PM by CoreyRoth

This is a bitter subject with most MOSS 2007 developers because the most common way to do this is by using a try/catch block when you try to use the indexer on SPListCollection.  Well, I am pleased to tell you about a new method I discovered on SPListCollection that really made my day.  The new TryGetList method takes the name of a list and will get this, return a null if the list doesn’t exist.  Take a look at this code.

using (SPSite siteCollection = new SPSite("http://moss-server"))

{

    SPList myCustomList = siteCollection.RootWeb.Lists.TryGetList("MyCustomList");

 

    // doesn't throw exception!

    if (myCustomList != null)

    {

        // do something

    }

}

That’s right!  You heard me, instead of throwing an exception, you actually get null back when the list doesn’t exist.  No more try/catch blocks.  No more extension methods to hide those try/catch blocks.  Unfortunately, there is nothing on SPBaseCollection to check if an item exists, but I do have a solution, so be looking for that post.

Comments

# Twitter Trackbacks for Checking to see if a list exists in SharePoint 2010 - Corey Roth - DotNetMafia.com - Tip of the Day [dotnetmafia.com] on Topsy.com

Pingback from  Twitter Trackbacks for                 Checking to see if a list exists in SharePoint 2010 - Corey Roth - DotNetMafia.com - Tip of the Day         [dotnetmafia.com]        on Topsy.com

# Sharepoint 2010 Blog – Luis Valencia » Using SPMonitoredScope

Pingback from  Sharepoint 2010 Blog – Luis Valencia » Using SPMonitoredScope

Leave a Comment

(required)
(required)
(optional)
(required)