0

As of a previous question, whenever an item is added in a list, I create a document library based on a template, and set defaultvalues for some of its fields. In Sharepoint Manager I see defaultvalues correctly set, but if I add an item to the document library, the fields are not filled with their expected default values: any hint? I am running Sharepoint Foundation 2013. This is the code:

public override void ItemAdded(SPItemEventProperties properties)
{
    SPWeb myWeb = properties.Web;
    string projectName = properties.ListItem["Project Name"].ToString();
    var customTemplate = myWeb.ListTemplates["ProjectTemplate"];
    Guid myItemGuid = myWeb.Lists.Add(projectName , projectName , customTemplate);

    SPList myItem = myWeb.Lists[myItemGuid];

    var projectCategoryField = myItem.Fields["Project Category"];
projectCategoryField.DefaultValue = "Test default value";
    projectCategoryField.Update();

    properties.ListItem.Update();
    base.ItemAdded(properties);
}
3
  • 1
    possible duplicate of Setting custom field default value within ItemAdded event
    – MdMazzotti
    Apr 20, 2015 at 9:34
  • 1
    I forgot to update the code sample according to your answer in that other question - that part was ok. The issue stated here is different - code is working but default value don't get filled.
    – RaffaeleT
    Apr 20, 2015 at 11:07
  • no need to create an exact duplicate of your previous question then. I would suggest that you delete this one and edit your other one
    – MdMazzotti
    Apr 20, 2015 at 11:34

2 Answers 2

1

There was not an issue with the code nor the Sharepoint edition. The issue was a somewhat scrambled list template, with multiple duplicate content types. I recreated it and everything is OK.

0

This should work for you.
You have to call the .Update() on the field not on the list.

public override void ItemAdded(SPItemEventProperties properties)
{
    SPWeb myWeb = properties.Web;
    string projectName = properties.ListItem["Project Name"].ToString();
    var customTemplate = myWeb.ListTemplates["ProjectTemplate"];

    myWeb.Lists.Add(projectName , projectName , customTemplate);
    SPList myItem = myWeb.Lists[projectName];

    //Is the field Project Category in your customTemplate
    SPField projectField= myItem.Fields["Project Category"];
    projectField.DefaultValue = "Test default value";
    projectField.Update()

    //properties.ListItem.Update();
    base.ItemAdded(properties);
}
1
  • Thank you, actually the code included Update() on the field - I forgot to update the code sample.
    – RaffaeleT
    Apr 20, 2015 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.