Question

I've got 2 lists: Companies and Employees. In Companies I have a text field called Name and in Employees I have a lookup to Companies based on the company Name.

What I'm trying to achieve is to get all Employees related to a specific company Name.

Gettting the related fields between the 2 lists:

SPList list = SPContext.Current.Web.Lists[ID];
SPRelatedFieldCollection relatedFields = list.GetRelatedFields();

Getting ALL the values from the child list:

SPList childList = SPContext.Current.Web.Lists[relatedFields[0].ListId];
SPFieldLookup lookupField = childList.Fields[relatedFields[0].FieldId] as SPFieldLookup;

foreach (SPListItem item in childList.Items)
{
    object rawValue = item[relatedFields[0].FieldId];
    if (rawValue !=null)
    {
        if (lookupField.AllowMultipleValues)
        {
            SPFieldLookupValueCollection values = item[relatedFields[0].FieldId] as SPFieldLookupValueCollection;

        }
        else
        {
            SPFieldLookupValue value = new SPFieldLookupValue(rawValue.ToString());
        }
    }
}

So how can I filter the child list to get only the specific employees from a single company(like Company = "Microsoft")? Keep in mind that 2 companies could have the same name, so I cannot based my solution on the value.

Thanks,

Was it helpful?

Solution

I think I was working too hard and needed a break from the code to see the obvious...

I found out that you have the SPListItem.ID on the parent item will give you the relation with SPFieldLookupValue.LookupId on the child item.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top