Thursday, May 19, 2011

Check list exists in SharePoint site

This is very generic issue all SharePoint developers face at initial stages. As there is no default method available in SharePoint API to check whether if list exists in the SharePoint site, everyone write the below code:
SPList list = web.Lists["Task List"];
If(list != null)
{ 
    //Some code on list.
}
This is not correct to code like this. We all know generics and collections in c#. SPWeb.Lists is a collection and if you want to get one object from collection either we need to pass index or the key. If that didn’t find in the collection it gives us the exception. So, in our example if the Sharepoint site don’t have list named “Task List” then you will give run time exception in the line 1 itself. So, there is no point of checking whether list object is null. So, here is where many people stuck at. As Lists is plain collection object there is no other way of checking for the list exists in collection other than below.
private static bool ListExists(SPWeb web, string listName)
{
try
{
SPList list = web.Lists[listName];
}
catch
{
return false;
}
return true;
}
I know what you are thinking [Is this solution right?]. Yes, unfortunately there is no other way. So, we have to use this to check whether list exists in a SharePoint site.

4 comments:

  1. Hi Praveen, this is my code for checking if lists exists or not?

    public static bool IsListExists(string strListName, SPWeb currentWeb)
    {
    bool isListExists = false;
    try
    {
    using (currentWeb)
    {
    isListExists = currentWeb.Lists.Cast().Any(list => string.Compare(list.Title, strListName, true) == 0);
    }
    }
    catch (Exception ex)
    { }
    return isListExists;
    }

    ReplyDelete
  2. use below code to check provided list existed or not

    SPList list = currWeb.Lists.TryGetList("survey");
    if(list!=null)
    {
    //some code
    }

    ReplyDelete
  3. Thank you Chakri for the solution. Will update the post.

    ReplyDelete
  4. TryGetList code will work for SharePoint 2010 and 2013 but for older version I guess Try and Catch code will be better.

    ReplyDelete