Search code examples
c#sharepointsharepoint-2010sharepoint-2013

Sharepoint 2013 GetItems parent id


I am new to sharepoint and I am trying to build a treeview list of parents and their respective children from an item list retrieved from sharepoint. In my code below, I use the "ID" fieldvalue to identify the item and the "parentleafname" lookupvalue to try determine whether this item has a parent. It appears though that the "ID" and lookupvalue from the "parentleafname" are the same. How can I get the parent id from the item in the list returned?

   private ListItemCollection GetList(string listName)
        {
            var web = _sharePointContext.Web;
            Microsoft.SharePoint.Client.List list = web.Lists.GetByTitle(listName);

            var query = new CamlQuery();

            query.ViewXml = "<View Scope=\"RecursiveAll\"> " +
                            "< Query >" +
                            "< OrderBy >" +
                            "< FieldRef Name = 'ID' />" +
                            "</ OrderBy >" +
                            "</ Query >" +
                            "</View>";

            query.FolderServerRelativeUrl = "/lists/" + listName;
            ListItemCollection folders = list.GetItems(query);

            _sharePointContext.Load(list);
            _sharePointContext.Load(list.Fields);
            _sharePointContext.Load(folders, fs => fs.Include(
                fi => fi["Title"],
                fi => fi["DisplayName"],
                fi => fi["FileLeafRef"],
                fi => fi["ParentLeafName"],
                fi => fi["ID"],
                fi => fi["ContentTypeId"]
                ));
            _sharePointContext.ExecuteQuery();


            return folders;
        }

Solution

  • This is not the best way of solving this problem, but it works. I managed to use the parent folder property ServerRelativeUrl which can be retrieved for each item in my list, as described here:

    Is there a way to get Folder object from ListItem one?

    I then built a parent/child hierarchy from the path (ServerRelativeURL) using this class:

    How to create hierarchical structure with list of path?