Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

TryGetList Method in SharePoint 2010

Hi

 Recently I noticed a method in 2010 object model. 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 oSite = SPContext.Current.Site;
            SPWeb oWeb = oSite.OpenWeb();
            SPList myList = oWeb.Lists["XYZ"];


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


            SPList myList = oWeb.Lists.TryGetList("XYZ");
            if (myList != null)
            {
               //your operations
            }

No comments:

Post a Comment