Aug 10, 2011

TryGetList method in 2010 OM

 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 the SPListCollection .Simply use this method instead of looping all the lists and check its existance


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



No comments:

Post a Comment