Just a quick note about an odd quirk I found today. While modifying an Item, you have to put it into Edit mode (using item.Editing.BeginEdit() ), however, if you change the Template of the Item (using item.ChangeTemplate(<newTemplate>) ), the next change you try to make will fail, because changing the Template pulls the Item out of Edit mode.
Here’s some example code that won’t work:
item.Editing.BeginEdit(); // Change to use the myItem template item.ChangeTemplate(myItemTemplate); // Fill in metadata item.Fields["Title"].Value = "myTitle"; item.Editing.EndEdit();
The above code errors when setting the Title field, because the item “isn’t in edit mode”, debugging the code confirms it, you can watch the isEditing flag go from True to False after the ChangeTemplate method is called.
The solution? ChangeTemplate doesn’t require the item to be in edit mode to run, so simply move it above the BeginEdit call, and you’re good to go. Here’s the fixed version of the above code:
// Change to use the myItem template item.ChangeTemplate(myItemTemplate); item.Editing.BeginEdit(); // Fill in metadata item.Fields["Title"].Value = "myTitle"; item.Editing.EndEdit();