Search code examples
c#sharepoint-2010lookupsplistitem

What´s the better way to get ID from lookup field value programmatically?


When I try to get the id from:

string idValue = item[Lookup].ToString();

I get the next value by example:

1;#1

I need the value this way:

1

Actually this code handle the requirement:

using (SPSite site = new SPSite(context.CurrentWebUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        //Context list                 
        SPList list = web.Lists[context.ListId];
        SPList child = web.Lists[List]; 
        SPListItem currentItem = list.GetItemById(context.ItemId);
        string updateItems = "";
        int ID = currentItem.ID;

        foreach (SPListItem item in child.Items)
        {
            string idValue = item[Lookup].ToString();
            int partial = idValue.LastIndexOf(";");
            string idPure = idValue.Substring(0, partial);

            if (idPure == ID.ToString())
            {
                item[Field] = Value;
                item.Update();
                updateItems += item.ID.ToString();
            }
        }              

        //Return Items*/
        results["Items"] = updateItems;
        SPWorkflow.CreateHistoryEvent(web, context.WorkflowInstanceId, 0,
            web.CurrentUser, TimeSpan.Zero, "Information",
            "Event from sandboxed, updates: " + updateItems, string.Empty);
    }
}

I want to know a better function or property to get the ID from lookup field.


Solution

  • SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(item["FieldName"].ToString());
    int lookupID = fieldLookupValue.LookupId;
    

    Here you go :)