Monday, March 18, 2013

SharePoint - Check list exists or not in a site using Trygetlist() method

In SharePoint, most of the data operations can be done through List\ Library. We can access the list in SPObjectModel to get the data. If site doesn't contain any list with given name, it will return null reference exception. To fix that we have a methods in SPObjectModel, TryGetList(String List Name).

Here is the code to analyse the both methods
  
SPList currentList=null;
using (SPSite currentSite = new SPSite("http://servername:5656"))
{
       using (SPWeb currentWeb = currentSite.OpenWeb())
       {
             currentList = currentWeb.Lists["MyList"];
          if(currentList!=null)
          {
                    Console.WriteLine(currentList.Title);
                    Console.ReadKey();
          }
       }
}
in the above code, if there is no list with name "MyList", it will return null reference exception in line SPList currentList = currentWeb.Lists["MyList"];  to avoid this we will write the code placing the line in try, catch block. But it is not a good to code to place try catch blocks regularly.

 In SPObjectModel we have a built in method "TryGetList(string List Name). If there is list with given name, it will return SPList object. If there is no list with given name it will return null.
  
SPList currentList=null;

using (SPSite currentSite = new SPSite("http://servername:5656"))
{
      using (SPWeb currentWeb = currentSite.OpenWeb())
      {
            currentList = currentWeb.Lists.TryGetList["MyList"];
      if(currentList!=null)
      {
                      Console.WriteLine(currentList.Title);
                      Console.ReadKey();
      }
      }
}
So that we can check null value.

Share this