Friday, June 5, 2009

Exception: Only String, int, and DateTime data types can be used as the value in Properties while adding list item in document library.

This is the exception I got when I try to add a list item through c# in a SharePoint document library.

Details:

In my previous post, I explained the logic for adding list item to a document library through c# code. This works well if the list/library columns are of type int, string and date time. If I add a column of type Currency then the code will break and it won't add the list item to the library at all. Because the function list.RootFolder.Files.Add() will not accept the properties other than the 3 types mentioned, through HashTable. This is the problem with the function. To avoid that below is the code i used and this problem went away.

Solution:

SPFile destfile = list.RootFolder.Files.Add(
fileName.Substring(fileName.LastIndexOf("\\") + 1), fs, true);
if (destfile.Item == null)
lblMsg.Text = "Error in adding file";
else
{
SPListItem listItem = destfile.Item;

//Logic to set list item columns like
//listItem["Title"] = "Document Title";
//listItem["CurrencyField"] = 234.908;
//listItem["NumberField"] = 12345.678;

listItem["ContentType"] = "Document"; //Default Content type for Document libraries
listItem.Update();
destfile.Update();
}

If you observe the code difference between my previous post and this post is, I am not passing the HashTable object to list.RootFolder.Files.Add() method. Because there the problem was. [Exception was coming from it.]

After I am adding the document then trying to set the column names of the list item by reading the same list item object which is from the line

SPListItem listItem = destfile.Item;

The below line to this line of code is for setting the content type of the document library. Take care of this one that, a document library can inherit from more than one content types. So you should mention the content type for better results.

Finally, updating the list item and updating the file to reflect the changes to the document library list items. Please feel free to post your ideas, comments and question here.

3 comments:

  1. Thanks mate for sharing it...it was some sort of help for me as i am quite new in sharepoint :)

    cheers
    /Aamir

    ReplyDelete
  2. Thank you so much... it really helped me.

    ReplyDelete
  3. Hi, I'm facing the same problem.
    Your solution is ok, but with this the finally version of the document (if versioning is active) will be 2 and not 1.
    I'm trying to add a double property using a string, and it works sometime... the problem is that if my site is in English then the string is '3.5' for example, but if the site is in Italian it does not work... In Italian the decimal separator is ",", but even with '3,5' it does not work...
    I thing the only (good) solution is to use your way and SystemUpdate().
    Have you any idea about?

    Thank you very much!

    ReplyDelete