Sign up ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

Given a custom list with folders for countries:

---FolderA (Title: "USA")
---FolderB (Title: "Switzerland")

Given a new custom list with country names:

---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:

---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

Update a Lookupfield from an item:

item[lookupFieldName] = ID;
share|improve this question

migrated from Aug 6 '12 at 14:03

This question came from our site for professional and enthusiast programmers.

1 Answer 1

up vote 1 down vote accepted

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;

    //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);
share|improve this answer
Thank you. This brings me a lot further :) I'm still digging the solution to get ListItemId by Title... –  Underlines Aug 6 '12 at 13:49
here's a hint, look at the indexer's that are available on the SPListItemCollection object (ListB.Items) –  Ken Henderson Aug 6 '12 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 '12 at 15:21

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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