我正在尝试读取SharePoint自定义列表中特定字段的值。
自定义列表包含以下字段:Field1,Field2和Field3
当我拨打以下代码时:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
foreach (var fieldValue in listItem.FieldValues)
{
Console.WriteLine(fieldValue.Key + ":" + fieldValue.Value + Environment.NewLine);
}
}
targetColumnValue = listItem[targetColumnName] as string;
return targetColumnValue;
}
错误消息是: 其他信息:属性或字段尚未初始化。尚未请求或请求尚未执行。可能需要明确请求。
foreach中显示的字段显示" Field1"和" Field2"。我是否必须明确要求" Field3"。如果是的话怎么样?
答案 0 :(得分:1)
出于某种原因,我必须在查询值之前获取内部名称。以下是有效的代码:
public static string GetLastTargetColumnValue(string sharePointSiteUrl, string sharePointListName, string targetColumnName)
{
string targetColumnValue = string.Empty;
using (var clientContext = new ClientContext(sharePointSiteUrl))
{
clientContext.Credentials = new NetworkCredential("userName", "password");
var list = clientContext.Web.Lists.GetByTitle(sharePointListName);
var field = list.Fields.GetByInternalNameOrTitle(targetColumnName);
var textField = clientContext.CastTo<FieldText>(field);
var query = CamlQuery.CreateAllItemsQuery(100);
var items = list.GetItems(query);
clientContext.Load(textField);
clientContext.Load(items);
clientContext.ExecuteQuery();
var listItem = items.Last();
targetColumnValue = listItem[textField.InternalName] as string;
}
return targetColumnValue;
}