0

Given a custom list with folders for countries:

ListA
---FolderA (Title: "USA")
------Item1
------Item2
------Item3
---FolderB (Title: "Switzerland")
------Item4
------Item5
------Item6

Given a new custom list with country names:

ListB
---Item1 (Title: "USA")
---Item2 (Title: "Switherland")

We have to move all Items in all folders to the root of the list. The Items contain a new Look-up field "Country" which looks up the ListB. When we move the items, it should set the lookupfield to the same as where the item was:

ListA
---Item1 (Lookupfield "Country" set to ID 1)
---Item2 (Lookupfield "Country" set to ID 1)
---Item3 (Lookupfield "Country" set to ID 1)
---Item4 (Lookupfield "Country" set to ID 2)
---Item5 (Lookupfield "Country" set to ID 2)
---Item6 (Lookupfield "Country" set to ID 2)

I don't need the finished code, just some generic hints.

What I have so far:

Get all items in the ListA, and check if it's not a folder:

if (item.Folder == null);

then get in which folder the item is:

item.Web.GetFolder(item.Url.Substring(0, item.Url.LastIndexOf('/')));
// I don't know if this works and I don't understand the solutions
// provided here http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/c0ca9f6b-ec1a-4e8d-b053-7969573370a4/

Update a Lookupfield from an item:

item[lookupFieldName] = ID;

1 Answer 1

1

Some rough code:

SPFolder rootFolder = ListA.RootFolder;
SPFolder folder = item.Folder;
if (folder != null)
{
    string folderName = folder.Name;
    //The details of this I'll leave up to you
    int lookupItem = GetListItemIdFromListBWithMatchingName(folderName);
    item[lookupFieldName] = lookupItem;
    item.Update();

    //This is the part that moves the item; note you may need something more robust
    //than my simple replace of the folder name.
    SPFile itemFile = web.GetFile(item.Url);
    string updatedUrl = itemFile.Url.Replace(folder.Name + "/", string.empty);
    itemFile.MoveTo(updatedUrl);
}
3
  • Thank you. This brings me a lot further :) I'm still digging the solution to get ListItemId by Title...
    – Underlines
    Aug 6, 2012 at 13:49
  • here's a hint, look at the indexer's that are available on the SPListItemCollection object (ListB.Items) Aug 6, 2012 at 13:56
  • public int get_ID(SPList list, string field, string itemname) { int id = 0; SPListItemCollection listItems = list.Items; foreach (SPListItem item in listItems) { if (item[field].ToString() == itemname.ToString()) id = item.ID; break; } return (id); } And then (NOT TESTED): string folder = sPListItem.Web.GetFolder(item.Url.Substring(0, item.Url.LastIndexOf('/'))).Name; sPListItem[regionInternalName] = get_ID(sourceList, "Title", folder);
    – Underlines
    Aug 6, 2012 at 15:21

Your Answer

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

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