我有一个名为“Designation”的列表,其中包含一个名称代码和名称名称。 我有另一个名为“Employee”的列表,其中包含Employee Name和Nameation Name(作为Lookup字段)。 我可以使用以下代码将值插入“Employee”列表。
protected void AddEmp(object sender, EventArgs e)
{
string emp_name = txtEmployeeName.Text;
string emp_designation = ddlDesignation.SelectedValue;
using (SPSite site = new SPSite("My Site"))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
web.AllowUnsafeUpdates = true;
SPList splist_employees = web.Lists["Employee"];
SPList splist_designations = web.Lists["Designations"];
SPListItemCollection splc_items = splist_employees.Items;
SPListItem spli_item = splc_items.Add();
SPFieldLookup lookup = splist_employees.Fields["Designated"] as SPFieldLookup;
string fieldName = lookup.LookupField;
spli_item["Employee Name"] = emp_name;
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations);
spli_item.Update();
});
}
}
}
public static string GetLookFieldIDS(string lookupValues, SPList lookupSourceList)
{
string id = string.Empty;
SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();
SPQuery query = new Microsoft.SharePoint.SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Designation' /><Value type='Text'>"+lookupValues + "</Value></Eq></Where>";
SPListItemCollection listItems = lookupSourceList.GetItems(query);
foreach (Microsoft.SharePoint.SPListItem item in listItems)
{
id = item.ID.ToString();
}
return id;
}
这里我在查询中给出了字段名称'Designation'。
但是,我希望根据用户端给出的值找到字段名称,而不是将字段名称硬编码为“指定”。
非常感谢任何帮助。提前谢谢。
答案 0 :(得分:0)
不确定您的请求但是,您可以将SPFieldLookup.LookupField属性传递给GetLookFieldIDS方法并使用该变量而不是“Designation”
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations, lookup.LookupField);