Wednesday, December 31, 2008

Accessing a list using SpWeb.Lists["listname"]

Recently, I tried deploying some code to production that opened up a list and added items into it. Sounds simple, and it worked great in my Test environment.
Simplified, the code looked something like this:

SPList myNewList = currentWeb.Lists["my list"];

Should work fine right?

After releasing to production, it would not work. I was getting:
"Value does not fall within the expected range."
(Wouldn't it be nice, if it told you what value did not fall within what range? That would make my life so much easier...)

Turns out, the list I was trying to open: "my list", wasn't originally named "my list". Someone had created the list as: "my list" (notice the two spaces), and then renamed it back. I checked the MSFT documentation on accessing a list using web.lists["name"], which is really the SPListCollection class ( http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistcollection.aspx )

It says:
"Use an indexer to return a single list from the collection. For example, assuming the collection is assigned to a variable named collLists, use collLists[index] in C#, or collLists(index) in Visual Basic, where index is the index number of the list in the collection, the display name of the list, or the GUID of the list."

WRONG! The display name, which I assume is the name that is listed on the list's Settings page as "Title", is not what it uses to look up the item. It uses the name that it is originally created as, the name that is in the URL.

I suppose this is good if you write code that uses the list name to get the list, and then later a user renames the list. Your code will still work.
It is a little odd that something like:
SPList myListCopy = myWeb.Lists[mylist.Title];
may not actually work.



EDIT:

The "Web Address:" on the List Settings page suffers from the List rename bug too. It will show the list using the List's title, and not the List's URL. If you rename the List, this web address will be wrong.

Monday, December 29, 2008

Email Enabling Custom Lists in MOSS

I was working with a list based on a Custon List definition today, and I wanted to email enable it. After playing around for a while and wondering why the link to email enable the list was not appearing on the settings page, I turned to google.

For some reason, you cannot email enable a list that is based on the custom list definition.

Solution: Use a different list type. I used Announcements because it's simple and doesn't have lots of extra columns that I don't want to use.