C# 以编程方式从查找字段值中获取 ID 的更好方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19307175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:42:08  来源:igfitidea点击:

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

c#sharepoint-2010lookupsplistitem

提问by Tabares

When I try to get the id from:

当我尝试从以下位置获取 id 时:

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

I get the next value by example:

我通过示例获得下一个值:

1;#1

1;#1

I need the value this way:

我需要这样的价值:

1

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.

我想知道一个更好的函数或属性来从查找字段中获取 ID。

采纳答案by Gintas K

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

Here you go :)

干得好 :)

回答by Omid Matouri

    SPList mySPList = oWeb.Lists["ProjectList"];
newItem["LookupFieldName"] = new SPFieldLookupValue(getLookUp(mySPList,LookupFieldValue), LookupFieldValue);



public static int getLookUp(SPList oList, string FieldValue, string sFieldName="Title")
        {

            foreach (SPListItem spi in oList.GetItems())
            {
                if (spi[sFieldName].ToString() == FieldValue)
                {
                    return spi.ID;
                }
            }
            return 0;
        }