Wednesday, August 13, 2008

Adding a Custom Content-Type Specific Item on a SharePoint List

I have a custom content type called “CustomItems” on my SharePoint list. I want to add an item to that list which will use the “CustomItems” content type. And i want to do it programmatically.

I don't know how to do it and I am finding the solution (yes still finding it). I have searched on google and find this site helpful

http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/

but after performing all the mentioned steps, i am getting this error:

"To Add an Item to a document Library, use SPFileCollection.Add()"

I have spent a whole week to find the solution and now i m posting it to help you all.

My requirement was to add a custom content type item in a document library, the above link is to add the item in a task list not in a document library that is why i was getting the error.

I had a custom content type Called "BIR-Form".

Following are the simple steps to do it:

  1. Upload this content type template anywhere in your site or place it on the file system at: "c:\windows\system32\inetsrv\ContentTypeTemplateFormName.xsn", i have used the second method.
  2. Write this code in your ItemAdded Event:


SPSite mySiteCollection = new SPSite("http://demo/");
SPWeb myWeb = mySiteCollection.RootWeb;

SPFolder folder = myWeb.GetFolder("CustomContentType");

FileStream fs = new FileStream("ContentTypeTemplateFormName.xsn.xsn", FileMode.Open);
byte[] fileContents = new byte[(int)fs.Length];
fs.Read(fileContents, 0, (int)fs.Length);
fs.Close();

SPFile file = folder.Files.Add("BIR.xsn", fileContents);
SPDocumentLibrary docs = (SPDocumentLibrary)myWeb.Lists[folder.ContainingDocumentLibrary];

SPContentType itemtype = myList.ContentTypes["BIR"];
SPListItem item = docs.Items[file.UniqueId];
item["ContentTypeId"] = itemtype.Id;
item.Update();

Change the value of fields and don't forget to call the update method.

3 comments:

Anonymous said...

Excellent Post, really helpful

Wildcard SSL said...

I found great information from your blog,keep posting this kind of stuff ahead.thanks for share with us.

Betty said...

This post is really helpful to me. I was trying to implement the same but the way you have carried out this task is really appreciating. I will follow your idea.
electronic signature for sharepoint