Copying list items from the master list to sub-sites
I have a site that contains its own master. I have several subsites that contain copies of this list. Whenever someone edits or adds a new list item to the master list, I would like all sub-sites to be updated appropriately by the event handler associated with the master list.
eg. if item is added add it to the list of every site
if the item is updated, update the corresponding list item for each site.
if an item is removed, remove the corresponding list item from each site.
I have tried using the SPListItem.Copy method as well as the CopyTo method for the listItem to no avail. What is the best practice for this kind of technique?
a source to share
I believe SPListItem.Copy and SPListItem.CopyTo will only work if the target list is in the same SPWeb as the original item. I am assuming there is an "identity" field in these list items, which not only distinguishes it from other list items, but is also always the same for all sub-sites and top-level site (as opposed to an ID which is not 100% under your control) ... It can be a name, it can be a programmed number, it can be anything. I'll just call this field "identity".
I assume you know event handlers. If you don't, you can see a very simple example here that explains all the basic concepts.
Removal is the easiest thing to handle. Simply iterate over the child items, iterate over the master list for the item with the correct "identity" field, and call SPListItem.Delete () on it. This should be enough to insert the ItemDeleting event.
The addition is a little trickier. Try again through the child nodes, but this time use the following method.
SPListItem target = list.Items.Add();
target["Title"] = properties.AfterProperties["Title"];
//Repeat similar assignments for all fields in the list item which can be assigned during creation.
target.Update();
This will need to be changed to include every field that can be changed, as well as the "identity" field if you haven't already. You don't have to worry about anything that gets automatically assigned (SharePoint will handle them anyway if Copy / CopyTo worked). Place it in the ItemAdded event.
Finally, updating an item is very similar to adding an item, except instead of calling list.Items.Add (), you instead get the correct item by iterating through the main list and getting the one with the correct "identity" field. Place it in the ItemUpdated event.
You might want to make sure that the child permissions for the master list are the same as for the top-level site. Hope this works for you!
a source to share