Reading vs. Updating objects in the SharePoint Object Model

A message came up on the newsgroup about someone having a problem with this code:

System.Guid listId=web.Lists.Add(title,description,web.ListTemplates["Document Library"],web.DocTemplates[0]);
web.Lists[listId].OnQuickLaunch=true;
web.Lists[listId].Update();

They were creating a list (a document library in this case) and wanted to display it on the Quick Launch. The code looked okay but the list wasn't being displayed on the Quick Launch. After a little experimenting (going down a couple of turkey trails like web part vs. console app) I found this slight change worked:

System.Guid listId=web.Lists.Add(title,description,web.ListTemplates["Document Library"],web.DocTemplates[0]);
SPList list = web.Lists[listId];
list.OnQuickLaunch=true;
list.Update();

I do remember passing by a document somewhere that said when accessing classes in the SharePoint namespace for updating to use the actual objects rather than an index of a collection. For whatever reason, I just naturally always get the list object myself so never came across this before. For reading purposes (like listing all the lists on a site) it's fine, but updates need to be implemented this way. I can't find that link right now but I did find a blog by Kris Syverstad from July of 2004 here on it to which Peter Provost thought maybe the WSS team implemented a property indexer when they probably should have implemented a method.

Looking through the newsgroups, this is probably one of the biggest "why doesn't my code work" message posted when it comes to updating properties. This tip will be true for any object in a collection (SPSite, SPList, SPField, etc.). Good stuff to know.

1 Comment

  • Bil,



    Thanks for posting that. After I made the initial posting on the NG, I tried getting a reference to the SPList that I just added and then updating that. Sure enough, it worked.



    Glad you posted this though as I'm sure there are plenty of people that have (or will soon) come across the odd behavior.





Comments have been disabled for this content.