- In the post we will see the new method TryGetList method of SharePoint 2010 object model to check if a list exists with a particular name or not using TryGetList method in SharePoint. Also you can check some SharePoint 2010 object model articles here
- This method belongs to class SPListCollection and it is available in SharePoint 2010, It was not there in MOSS 2007.
- This will be available in Sandboxed Solutions also.
- Syntax of TryGetList method:
public SPList TryGetList ( string listTitle )
Here listTitle is the title of list and it returns a SPList object.
- But if the list is not available then it will not give any exception as it was giving in MOSS 2007, rather it will return NULL value.
- Previously we usually retrieve like below:
SPList list = web.Lists["OurListName"];
But here if the list does not exists then it will throw an exception.
- Code sample for TryGetList method:
using ( SPSite site = new SPSite ( "http://Top Site URL" ) )
using ( SPWeb web = site.RootWeb )
SPList list = web.Lists.TryGetList("Our List Name");
if ( list != null )
// We found the List
//If List does not exists then it will not through any exception, it will return Null