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.

0 komentar:

Post a Comment

Related Posts with Thumbnails
GiF Pictures, Images and Photos