Pages

Subscribe:

Tuesday, January 10, 2012

TryGetList method in SharePoint 2010

Generally when we writing the code to get a list from the web, we will get  the error if the list does not exist. For that we will loop through the lists collection and checks whether it exists or not

           SPSite Site = SPContext.Current.Site;
            SPWeb Web = Site.OpenWeb();
            SPList  List = Web.Lists["List Name"];


If there is no list with the name ListName, it throughs null reference exception. To avoid this, In 2010 OM a new method is introduced in the SPListCollection .Simply use this method instead of looping all the lists and check its existance

            SPList List = Web.Lists.TryGetList("List Name");

            if (List != null)
              {
                 Response.Write("List Exist");
              }
           else 
                 Response.Write("List Doesnot Exist");

Happy Coding..!!!!

No comments:

Post a Comment