Home > Object Model, Share Point, SharePoint 2010 > SharePoint: Getting a SPList with no exceptions to be thrown

SharePoint: Getting a SPList with no exceptions to be thrown

List 'some list name' does not exist at site with URL 'some site url'.

    Getting a SPList object in code, I prefer not using an indexer of the SPWeb.Lists collection (SPListCollection) as it throws the above exception every time when the list with the specified name wasn’t found in the collection. It should be noted, however, that in SharePoint 2010, there is the TryGetList method, that has been added to SPListCollection and which returns null if the list isn’t presented in the collection. But I still use my own simple methods free of ‘not found’ exceptions and compatible with both SharePoint 2007 and 2010.

Get SPList by title

The first method returns a SPList object by specified title or null if nothing is found:

public static SPList GetListByName(SPWeb web, string listName)
{
    listName = listName.ToLower();
    foreach (SPList spList in web.Lists)
        if (spList.Title.ToLower() == listName)
            return spList;
    return null;
}

// usage
// ...
    using (SPSite spSite = new SPSite("some site url"))
        using (SPWeb spWeb = spSite.OpenWeb())
        {
            SPList spList = GetListByName(spWeb, "Products");
        }
// ...

Get SPList by url

Unfortunately, list title tends to be changed in the course of time. Unlike title, list url is unchangeable in list’s life time. So, the use of url (or its part) for list search is more reliable. The second method exactly uses url to find a list:

public static SPList GetListByUrl(SPWeb web, string url)
{
    url = url.ToLower();
    foreach (SPList spList in web.Lists)
        if (spList.RootFolder.Url.ToLower().EndsWith(url))
            return spList;
    return null;
}

// usage
// ...
    using (SPSite spSite = new SPSite("some site url"))
        using (SPWeb spWeb = spSite.OpenWeb())
        {
            SPList spList = GetListByUrl(spWeb, "Lists/Products");
        }
// ...

I hope these methods would be useful for somebody else.

Related posts:
 
  1. No comments yet.
  1. No trackbacks yet.