嗨,谢谢你的期待!
当我尝试将值添加到查阅列时,我遇到了问题。
我正在使用SharePoint 2007,该应用必须在.NET 2.0中运行。语言是C#。 某些查阅列将允许多个值。
使用C#,我该怎么做#以下2-4的内容:
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.RootWeb)
{
SPList customerList = web.Lists.TryGetList("Contoso Customers");
SPList orderList = web.Lists.TryGetList("Contoso Orders");
if (customerList != null && orderList != null)
{
SPListItemCollection customers = customerList.Items;
SPListItemCollection orders = orderList.Items;
string fieldName = "CustIDLookup";
if (!orderList.Fields.ContainsField(fieldName))
return;
SPField lookupFld = orderList.Fields.GetField(fieldName);
foreach (SPListItem customer in customers)
{
SPListItem order = orders.Add();
order[SPBuiltInFieldId.Title] = "Thank you!";
order.Update();
SPFieldLookupValue value = new SPFieldLookupValue(customer.ID, customer.ID.ToString());
order[lookupFld.Id] = value.ToString();
order.Update();
}
}
}
}
}
}
}
即使有微软的例子,我也无法确定如何实际做到这一点。
非常感谢您的帮助。
答案 0 :(得分:0)
//untested pseudocode - hope this points you in the right direction
SPList lookupItems = ... // add code here
SPList list = ... // add code here
string lookupFieldName = "LookupValue"; // change to the appropriate value
foreach(SPListItem item in list.Items)
{
string value = (string)item[lookupFieldName];
if(value.Contains("#")) // value containing hash is most likely a lookup value already
{
// use SPFieldLookupValue to get actual value
SPFieldLookupValue currentValue = new SPFieldLookupValue(value);
value = currentValue.LookupValue;
}
// Get the list item (you will need this to find out its id value)
SPListItem lookupItem = GetLookupListItem(lookupList, value);
if(lookupItem == null)
{
//If it doesn't exist, create it
lookupItem = AddNewLookupItem(lookupList, value);
SPFieldLookupValue lookupValue = new SPFieldLookupValue(lookupItem.ID,value));
item["LookupValue"] = lookupValue.ToString();
item.Update();
}
}
SPListItem GetLookupListItem(SPList lookupList, string value)
{
// iterate through list to find item
// use a list query if the list is too big for this to perform well (see here: http://msdn.microsoft.com/en-us/library/ie/ms456030.aspx)
foreach(SPListItem item in lookupList)
{
string itemValue = (string)item[0]; // assuming lookup list has one field of type string containing lookup value
if(value == itemValue)
{
return item;
}
}
return null;
}
SPListItem AddLookupListItem(SPList list, string value)
{
SPListItem newItem = list.Add();
newItem[0] = value;// assuming lookup list has one field of type string containing lookup value
newItem.Update();
}