Sharepoint 如何获取SPFieldLookup的所有可能值
我在sharepoint中有一个查找字段,它只引用另一个列表。我想知道如何通过编程枚举此字段的所有可能值? 例如,我的查找字段“实际城市”指的是列表“城市”和列“标题”,我有3个城市。在代码中,我想得到字段“实际城市”的所有可能值的列表,类似于smth(元代码,对不起):Sharepoint 如何获取SPFieldLookup的所有可能值,sharepoint,spfield,Sharepoint,Spfield,我在sharepoint中有一个查找字段,它只引用另一个列表。我想知道如何通过编程枚举此字段的所有可能值? 例如,我的查找字段“实际城市”指的是列表“城市”和列“标题”,我有3个城市。在代码中,我想得到字段“实际城市”的所有可能值的列表,类似于smth(元代码,对不起): SPFieldLookup f=myList[“实际城市”] 集合availableValues=f.GetAllPossibleValues() //这将返回用户可能为该字段选择的所有城市的集合 我认为没有明确的方法返回您
SPFieldLookup f=myList[“实际城市”]
集合availableValues=f.GetAllPossibleValues()
//这将返回用户可能为该字段选择的所有城市的集合
我认为没有明确的方法返回您想要的内容。但是该类存储了手动请求此信息所需的所有信息:和
因此,您可以通过从查找字段使用的列表中获取信息来检索信息。为了使其可重用,您可以将其作为一个组件来实现。因此,下次您可以真正调用
f.GetAllPossibleValues()代码>据我所知,您想查询所有正在使用的值吗
如果是这样,您必须查询实际城市不为空的项目,查询结果如下:
<Where><IsNotNull><FieldRef Name='Actual City'/></IsNotNull></Where>
然后,对于每个查询的项目,您将
List<SPFieldLookupValue> result = new List<SPFieldLookupValue>(returnedItemCount * 5);
foreach (SPListItem item in queriedItems) {
object lookup = item["Actual City"];
SPFieldLookupValueCollection lookupValues = new SPFIeldLookupValueCollection(
(lookup != null) ? lookup.ToString() : ""
);
foreach (SPFieldLookupValue lookupValue in lookupValues) {
if (!result.Contains(lookupValue)) {
result.Add(lookupValue);
}
}
}
List结果=新列表(returnedItemCount*5);
foreach(queriedItems中的SPListItem项){
对象查找=项[“实际城市”];
SPFieldLookupValueCollection lookupValues=新SPFieldLookupValueCollection(
(lookup!=null)?lookup.ToString():“”
);
foreach(查找值中的SPFieldLookupValue lookupValue){
如果(!result.Contains(lookupValue)){
结果。添加(查找值);
}
}
}
或者您可以使用HashTable,其中LookupId是string,LookupValue是int-id,然后检查HashTable.ContainsKey(LookupId)
。。。在哈希表中查找整数必须比在列表中查找字符串更快,但资源密集型部分可能是查询该字段包含某些值的所有项目,然后循环…如果要枚举所有可能的值,这意味着您基本上要从城市列表中的所有项目中获取所有标题字段值。我不认为SharePoint中有像GetAllPossibleValues()这样的方法,但是你可以列出城市中的所有项目并获取它们的标题(如果只有几个),或者如果有很多,可以使用CAML查询。前几天我为我的项目编写了一些代码来处理这个问题。也许会有帮助
public static List<SPFieldLookupValue> GetLookupFieldValues(SPList list, string fieldName)
{
var results = new List<SPFieldLookupValue>();
var field = list.Fields.GetField(fieldName);
if (field.Type != SPFieldType.Lookup) throw new SPException(String.Format("The field {0} is not a lookup field.", fieldName));
var lookupField = field as SPFieldLookup;
var lookupList = list.ParentWeb.Lists[Guid.Parse(lookupField.LookupList)];
var query = new SPQuery();
query.Query = String.Format("<OrderBy><FieldRef Name='{0}'/></OrderBy>", lookupField.LookupField);
foreach (SPListItem item in lookupList.GetItems(query))
{
results.Add(new SPFieldLookupValue(item.ID, item[lookupField.LookupField].ToString()));
}
return results;
}
如果查找列表位于其他站点(例如站点查找列),则此操作将失败。要检查列表所在的站点,请检查lookupField.lookupWebId-
var list = SPContext.Current.Web.Lists["My List"];
var results = GetLookupFieldValues(list, "Actual City");
foreach (SPFieldLookupValue result in results)
{
var value = result.LookupValue;
var id = result.LookupId;
}