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.

0 komentar:

Post a Comment

Related Posts with Thumbnails
GiF Pictures, Images and Photos