2013-10-10 49 views
4

當我試圖從獲得ID:以編程方式從查找字段值獲取ID的更好方法是什麼?

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

我得到例如下一個值:

1;#1

我需要的價值是這樣的:

其實這個代碼處理要求:

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); 
    } 
} 

我想知道一個更好的功能或屬性來獲取從查找字段的ID。

+0

分割值 「#」,並採取第一部分 –

+0

這也很有幫助[get和set一個SharePoint查閱字段值使用SSOM C#(HTTPS: //social.technet.microsoft.com/wiki/contents/articles/40271.get-and-set-a-sharepoint-lookup-field-values-using-ssom-c.aspx) –

回答

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

在這裏你去:)

0
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; 
     } 
+0

您能否詳細說明並解釋/爲什麼這是比已發佈的更好的方式? –

相關問題