Monday, January 24, 2011

Checking to see if a list exists in SharePoint 2010

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

}
}

No comments: