Posted by: R Manimaran | March 29, 2011

Check the SharePoint List Exists or not -SharePoint 2007 and SharePoint 2010

Check the SharePoint List Exists or not –SharePoint 2007 and SharePoint 2010

While using Object model in SharePoint 2007 we use to check the existence of a List using the SharePoint List Collection as below.


SPList myList = web.List["Sample List"];


In the above case if the specified list is found, then the corresponding list object get loaded in myList variable. But if the list does not exist, in that case it will throw Argument Exception. To get rid of this we use to have try-catch section to handle the exception.

Instead we can use the LINQ to handle this in easier way.


SPList myList = web.Lists.Cast<SPList>().FirstOrDefault(l => l.Title == "Shared Documents");

Here if the specified list is not found then myList will get assigned to null value. The same can be used for SPContentType, SPField and so on as below.


SPContentType myContentType = web.ContentTypes.Cast<SPContentType>().FirstOrDefault(c => c.Name == "Employee");

SPField mySiteCol = web.Fields.Cast<SPField>().FirstOrDefault(f => f.Title == "EmpId");

New in SharePoint 2010 – TryGetList

In SharePoint 2010, for handling the null while checking for a list is automatically done by a method. We have a new Method called TryGetList which is available in SPListCollection class.


using (SPSite site = new SPSite("http://SharePointServer"))

{

using (SPWeb web = site.OpenWeb())

{

SPList myList = web.Lists.TryGetList("Employees");

}

}

Here if the specified list is not available in the Collection, null will be assigned to the myList.

Advertisements

Responses

  1. Thanks, I made it more simple.
    http://sasikumarreddyv.blogspot.in/2012/02/how-to-check-if-list-exists-or-not-in.html


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: