1 out of 1 rated this helpful - Rate this topic

SPListCollection.TryGetList Method

SharePoint 2010

Returns the list with the specified title from the collection, but returns null instead of an exception if the list does not exist.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online
public SPList TryGetList(
	string listTitle
)

Parameters

listTitle
Type: System.String
A string that contains the title of the list.

Return Value

Type: Microsoft.SharePoint.SPList
An SPList object that represents the list.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Invalid code example
using (SPSite oSiteCollection = SPContext.Current.Site)
    {
        try
        {
              using (SPWeb oWebsiteRoot = SPContext.Current.Web)
              {

Take care if you really use this code (example?).

  • oSiteCollection isn't used
  • Disposing shouldn't be done on SPContent.Current....
Add an overload to be able to check if a list exist by its URL
It would be great if there would be an overload to the method TryGetList to verify if a list exist by it's URL instead of it's display name (which can change often).

Ex :

Public Shared Function TryGetListByUrl(ByVal web As SPWeb, ByVal urlList As String) As SPList
Try
Return web.GetList(urlList)
Catch ex As Exception
Return Nothing
End Try
End Function

how i use it..
  

protected void WorkWithList()
{
    using (SPSite oSiteCollection = SPContext.Current.Site)
    {
        try
        {
              using (SPWeb oWebsiteRoot = SPContext.Current.Web)
              {
                    TargetURL = HttpUtility.UrlPathEncode(TargetURL);
                    //usual method
                     try
                     {                           
                        SPList oList = oWebsiteRoot.GetListFromUrl(SPContext.Current.Web.Url + "/Lists" + TargetURL + "/AllItems.aspx");
                        //carry out list operations
                     }
                     catch (SPException spe)
                     {
                         //cannot find list or columns not correct
                     }
 
                     //alternative if referencing list from list
//title no exception handling required in theory
//as null returned if list not found
                     SPListCollection oListCollection = oWebsiteRoot.Lists;
                     SPList oList2 = oListCollection.TryGetList("youlist");
 
               }
         }
         catch (Exception ex)
         {
             //problem getting to list
         }
    }
}

Felt the absence of this method in SharePoint 2007.
I have described in my blog  how we are used to write code in SharePoint 2007 to check if the list exists or not.
"http://ranaictiu-technicalblog.blogspot.com/2010/04/sharepoint-2010-new-method-added-to.html