views:

137

answers:

2

I have a site which contains a custom list Master. I have a number of sub sites which contain copies of this list. When someone edits or adds a new list item to the master list, I would like all sub sites to be updated accordingly by an event handler which is associated with the master list.

e.g. if item is added, add it to the list of each sub site

if item is updated, update the appropriate list item of each sub site

if item is deleted, delete the appropriate list item from each sub site

I have tried using the SPListItem.Copy method and also the CopyTo method of the listItem to no avail. What is the best practice of doing this kind of technique?

+1  A: 

I believe that SPListItem.Copy and SPListItem.CopyTo will only work if the target list is on the same SPWeb as the original item. I'm assuming that these list items have some "identity" field which not only distinguishes it from the other list items, but also is always the same across all of the subsites and the top level site (unlike ID, which isn't 100% under your control). Could be the title, could be a programmatically assigned number, could be anything. I'll just call this the "identity" field.

I am assuming you know Event Handlers. If you don't, you can see a very basic example here that explains all the core concepts.

Deleting is the easiest thing to handle. Just iterate through the subsites, iterate through the Master list for the item with the correct "identity" field, and call SPListItem.Delete() on it. That should be sufficient to put in an ItemDeleting event.

Adding is slightly more difficult. Once again iterate through the subsites, but this time use a method like follows.

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 have to be modified to include every field which can be modified, as well as the "identity" field if you didn't already include it. You shouldn't have to worry about anything which would be automatically assigned (SharePoint would handle them anyway if Copy/CopyTo had worked). Put it in an ItemAdded event.

Finally, updating the item is very similar to adding an item, only instead of calling list.Items.Add(), you instead get the correct item by iterating through the Master list and getting the one with the correct "identity" field. Put it in an ItemUpdated event.

You might want to make sure that permissions on the subsites for the Master List are the same as on the top level site. Hope this works for you!

ccomet
Thanks - great answer.
Graeme
A: 

If it is a master list that you want to use as a lookup column, you can create the list in your root site and then point a site column to it. That site column can then be used in any of your subsite lists.

KoenVosters
Can you explain this a bit more?
mandroid