SharePoint User Group UK

Share the knowledge!

Welcome to SharePoint User Group UK Sign in | Join | Help
in
Home Blogs Forums Photos Files Roller

Toms Blog

Adding SPListItems in SharePoint 2007

OK, so for my first real post I'd like to do go through programatically adding an item to a SharePoint List. It's pretty simple, but there are some things that it took me quite some time to find out. Please excuse me if I'm going through easy stuff, its been a hectic three months finding out all this =). I'm using the Beta 2 with a MOSS  on a VPC.

Lets look at some C# code:
___________________________________________

  SPList myList = myWeb.Lists["My First List"];
  SPListItem myNewItem = myList.Items.Add();
  myNewItem["Title"] = "New Item";
 
myNewItem.Update();
___________________________________________

So in the first line I got a SharePoint list from my SPWeb object. Then I used the Add() method of the Items collection which creates and returns a new SPListItem. Then, since one usually wants to initalize a new item with some values, I've set the "Title" property of my item and then used Update() to push the changes to the database.


All nice and easy. Some problems here though: what we get is an item using the default content type and maybe we have several in one list. Lets' modify our code to change the content type while creating an item:
___________________________________________

*SPContentType myCType = myList.ContentTypes["Custom content type"];
  SPList myList = myWeb.Lists["My First List"];
  SPListItem myNewItem = myList.Items.Add();

*myNewItem["ContentTypeId"] = myCType.Id;
*myNewItem.Update();

  myNewItem["Title"] = "New Item";
*myNewItem["CustomSiteColumn"] = 3;
  myNewItem.Update();
___________________________________________

To change the item content type, I need my list content type Id. It's best to get this from the actual SPList object, than to have it hard-wired. myList.ContentTypes returns a collection of c.types from which I can get the one I need through an indexer. It's also best to check if the content-type exist with something like an if (myCType != null) block, but for this example I'll assume it's all set up. Next thing there is changing the "ContentTypeId" field of the new item. Then an update and yey! we can access the "CustomSiteColumn" field of our new item.

For those of you wracking your brains how I knew about ContentTypeId field it can be educational to run a foreach on all the fields of your SPListItem.Fields like the following:
___________________________________________
foreach (SPField f in myItem.Fields)
{
    try
    {
         if (myItem[f.Title] != null)
         {
             Label1.Text +=
                f.TypeAsString + " "
             + f.Title + " "
             + f.InternalName + " "
             + thisItem[f.InternalName] + "<br />";
         }
     }
     catch (Exception ex)
     {
         Label1.Text = "Non-accessable field.<br />";
     }
}
___________________________________________

This little snippet of code will print all the fields inside your SPListItem for you to examine. I found out about the "Path" property this way.
Anyhow back to our example. So we've programatically created a new list item.. but where? In the root folder most likely, depending on what Item collection we were opening I think. But lists also support folders and we'll often want to stick our item in a particular folder.. for instance for security reasons, or just to keep things nice and tidy. Lets try creating an item in a folder then:
___________________________________________

 
SPContentType myCType = myList.ContentTypes["Custom content type"];
  SPList myList = myWeb.Lists["My First List"];
*
SPFolder myFolder = dm.myList.Folders[3];
*
SPListItem myNewItem = dm.myList.Items.Add(myFolder.ServerRelativeUrl, SPFileSystemObjectType.File, null);

  myNewItem["ContentTypeId"] = myCType.Id;
  myNewItem.Update();

  myNewItem["Title"] = "New Item";
 
myNewItem["CustomSiteColumn"] = 3;
  myNewItem.Update();
___________________________________________

Look at the second new line: there's the overloaded .Add() method of the SPListItemColection, which now accepts a Url, an object type and a leafName. The first is most important - the url of the folder where our new item is going to be placed. When programatically accessing SharePoint its best to grab the url from some object.. like the SPFolder object we want to stick our item in. Next thing we need is the SPFileSystemObjectType.. basically either File, Folder or Web. Now it gets complicated - behind each SPListItem there is an SPFile object with the same Guid. Same with a list folder. Each folder also has an Item object.

I'll try to go into that in more detail (how I understand it) later, for now it'll do to say you can add an SPFolder to the SPList the same way as in my example, except you use
SPFileSystemObjectType.Folder. And as for the leafName - that's autogenerated so just put null.

So that just about wraps it up. Don't forget to run myWeb.Dispose() on your SPWeb objects after you've finished with them..

Thomas Prentis

=8)-DX
Published 28 September 2006 19:15 by dxman
Filed Under: ,

Comments

 

Sirk said:

Do you know how to change the default content type of a list using the object model? I can't seem to find any property that allows me to do that. (ie I want to change the default content type for the pages list to "MyCustom Content Type")

I can do it through the UI, but I also need to be able to do it through the object model.
October 10, 2006 19:42
 

ssa said:

Excellent post! Very comprehensive and detailed! Simple awesome!

SharePoint Pakistan User Group
http://sharepoint.walisystems.com

--
November 9, 2006 10:25
 

amishjt said:

Hi Tom,

I am trying to add an item with custom content type in a document library but the code doesnot work. When i try to use the code above. It throws an excpetion saying use SPFileCollection.Add method to add a file. Any ideas as to how can we add an item and change the default content type of the item in a document library. Is it even possible.

Thanks in Advance.
August 28, 2007 23:37
 

SaurabhKV said:

SPSite site = new SPSite(&quot; http://[ServerName/sitename ]&quot;); SPWeb web = site.OpenWeb(); SPList list =
June 9, 2008 15:37
Anonymous comments are disabled

This Blog

Post Calendar

<September 2006>
MoTuWeThFrSaSu
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

Syndication

Powered by Community Server, by Telligent Systems