add

Monday, April 27, 2009

How to check whether SPList exists in Sharepoint?

Sometimes we require to check whether SPList exists or not. There is no direct method to check for it. Instead we have to use try-catch block to catch the exception and to determine the list existence:

The code is:


using (SPSite ospSite = new SPSite("http://<servername>:<portname>"))
{
using (SPWeb ospWeb = ospSite.OpenWeb())
{
try
{
SPList ospList = ospWeb.Lists["ListName"];
if (ospList != null)
return true;
}
catch(Exception ex)
{
return false;
}
}
}


This code block creates an instance of SPList object. If ospList object is not null that is list is there so it returns true.
If list does not exists, an exception will be raised and false will be returned from catch block

1 comment:

Unknown said...
This comment has been removed by the author.