January 4, 2011

Ways to Get SPList Object In Your C# Code

I was looking at a code that I wrote for m=one of my projects earlier today and here is the code snippet that I was got my attention and made me think if there is a better way to retrieve the SP list in my methods:

//web is an SPWeb object created somewhere earlier in my code

SPList list = web.Lists["Tasks"];

Right away I can see two issues:

If that list doesn’t exist, then my code will blow up.

What if the list exists but one of the power users renames it? then again, my code will blow up

Problem: code blowing up if list title does not exist in the SPListCollection object under SPWeb.Lists!

Solution 1: Wrap your code with a try catch block

SPList list = null;

try

{

//web is an SPWeb object created somewhere earlier in my code

list = web.Lists["Tasks"];

}

catch

{

//Log this or do whatever you feel like doing to report the issue

}

This will stop your code from firing an exception, but now there is a big chance of getting this exception especially in an environment where users keep changing stuff around the site. so no love for this solution (in my opinion) as it does solve issue #1 but not #2.

Solution 2: Create a method that will enumerate through the SPListCollection and find that title or return null

publicstatic SPList GetListByTitle(SPWeb web, string listTitle)

{

foreach (SPList list in web.Lists)

{

if (list.Title.Equals(listTitle, StringComparison.InvariantCultureIgnoreCase))

{

return list;

}

}

returnnull;

}

This method will now fire any exceptions and return null back to the caller if the list was not found.

This was the solution I implemented for the project I worked on. BUT I knew there is a better way to doing that as this still does not solve my issue #1 but not #2

Solution 3: get list by URI instead of Title (Optimal)

publicstatic SPList GetListByUrl(SPWeb web, string listUrl)

{

return web.GetList(web.Url + listUrl);

}

Now this is a solution that I like, as the list URI will never change, even if the user changes the list title. I wonder why I haven’t thought of this one before!