- 适用版本:SharePoint Server 2010及以上
- 面向用户:开发者
- 难度指数:★★★☆☆
本文主要是整理记录下,如何通过SharePoint在服务端对象模型中如何对列表各种字段类型赋值和取值操作。
获取列表中和一个 SPListItem
这是得到SPListItem的基本代码。如果列表中包含至少一条数据,检索的第一项,否则创建新项目。
var web = SPContext.Current.Site.RootWeb;
var list = web.Lists.TryGetList("fieldslist");
if (list == null) return;
SPListItem item;
item = list.ItemCount > 0 ? list.Items[0] : list.Items.Add();
创建示例中所使用的变量
var t = DateTime.Now.ToLongTimeString();
//StringBuilder for output
var s = new StringBuilder();
//Variable for storing temporary values
String value;
赋值、取值示例
设置和获取标题
- 赋值
item["Title"] = String.Format("Title updated at {0}",t);
- 取值
value = item["Title"].ToString();
s.AppendLine(String.Format("Title Field: {0}<br></br>", value));
设置和获取文本字段
- 赋值
item["textfield"] = String.Format("At {0} dogs still can't write poems", t);
item.Update();
- 取值
value = item["textfield"].ToString();
s.AppendLine(String.Format("Text Field: {0}<br></br>", value));
多行文本(或富文本)字段
- 赋值
item["notefield"] = String.Format("At {0} dogs still can't write poems. \r\nBut then, neither can I!", t);
item.Update();
- 取值
value = item["notefield"].ToString();
s.AppendLine(String.Format("Note Field: {0}<br></br>", value));
设置和获取Yes/No 字段(布尔值)
- 赋值
item["yesnofield"] = false;
item.Update();
- 取值
value = item["yesnofield"].ToString();
s.AppendLine(String.Format("Yes/No Field: {0}<br></br>", value));
设置和获取数字字段
- 赋值
item["numberfield"] = 35;
//Or
item["numberfield"] = Double.Parse("354.67");
item.Update();
- 取值
value = item["numberfield"].ToString();
s.AppendLine(String.Format("Number Field: {0}<br></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F1");
s.AppendLine(String.Format("Number Field (one decimal place): {0}<br></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F0");
s.AppendLine(String.Format("Number Field (two decimal places): {0}<br></br>", value));
设置和获取货币字段
货币字段使用字段类型相同的 SharePoint 作为数 (SPFieldNumber)。数字字段的类型是double。您可以使用标准数字格式指定要设置格式的数字显示,具体地说,格式化为一种货币。请参阅Double.ToString的详细信息。
- 赋值
item["currencyfield"] = Double.Parse("354.67");
item.Update();
- 取值
value = item["currencyfield"].ToString();
s.AppendLine(String.Format("Currency Field: {0}<br></br>", value));
value = Double.Parse(item["currencyfield"].ToString()).ToString("C2");
s.AppendLine(String.Format("Currency Field (formatted as a currency): {0}<br></br>", value));
value = (Double.Parse(item["numberfield"].ToString()) + 123).ToString("C2");
s.AppendLine(String.Format("Currency Field (addition): {0}<br></br>", value));
设置和获取百分百的字段
百分比字段使用字段类型相同的 SharePoint 作为数 (SPFieldNumber)。数字字段的类型是double。您可以使用标准数字格式指定要设置格式的数字显示,具体地说,格式为百分比。请参阅Double.ToString的详细信息。
- 赋值
item["percentfield"] = Double.Parse("0.8735");
item.Update();
- 取值
value = item["percentfield"].ToString();
s.AppendLine(String.Format("Percent Field: {0}<br></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P0");
s.AppendLine(String.Format("Percent Field (formatted as a percent, and as a whole number): {0}<br></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P2");
s.AppendLine(String.Format("Percent Field (formatted as a percent, with two decimal places): {0}<br></br>", value));
设置和获取日期字段
若要设置一个日期字段,使用 System.DateTime 对象创建一个日期,然后将 DateTime 对象分配给列表项的字段。当您检索日期时间字段的值时,可以使用标准日期格式说明符来设置格式的值的输出。请参阅DateTime.ToString的详细信息。
- 赋值
item["datefield"] = DateTime.Now;
//Or, set the date to Now + two days
item["datefield"] = DateTime.Now.AddDays(2);
item.Update();
取值
value = item["datefield"].ToString();
s.AppendLine(String.Format("Date Field: {0}<br></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("d");
s.AppendLine(String.Format("Date Field (using the \"6/15/2008\" format): {0}<br></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("D");
s.AppendLine(String.Format("Date Field (using the \"Sunday, June 15, 2008\" format): {0}<br></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("R");
s.AppendLine(String.Format("Date Field (using the \"Sun, 15 Jun 2008 21:15:07 GMT\" format): {0}<br></br>", value));
var dateValue = DateTime.Parse(item["datefield"].ToString());
value = dateValue.AddDays(13).ToString("dd-MMM-yy");
s.AppendLine(String.Format("Date Field (using a custom display format): {0}<br></br>", value));
设置和获取单择字段
单选赋值
var choicevalues = new SPFieldMultiChoiceValue();
choicevalues.Add("Green");
choicevalues.Add("Blue");
item["multiplechoicefield"] = choicevalues;
item.Update();
单选取值
value = item["choicefield"].ToString();
s.AppendLine(String.Format("Choice Field: {0}<br></br>", value));
设置和获取多选择字段
多选取值
list.Fields["multiplechoicefield"].ParseAndSetValue(item, choicevalues.ToString());
var multipleChoiceValues = new SPFieldMultiChoiceValue(item["multiplechoicefield"].ToString());
s.AppendLine(String.Format("Multiple Choice Field: {0}<br></br>", multipleChoiceValues));
for(int i = 0; i Multiple Choice Field, value {0}: {1}<br></br>", i, multipleChoiceValues[i]));
}
多选赋值
var choicevalues = new SPFieldMultiChoiceValue();
choicevalues.Add("Green");
choicevalues.Add("Blue");
item["multiplechoicefield"] = choicevalues;
item.Update();
设置和获取单用户字段字段
单用户取值
value = item["personfield"].ToString();
s.AppendLine(String.Format("Person Field: {0}<br></br>", value));
var userFieldValue = new SPFieldUserValue(web, item["personfield"].ToString());
s.AppendLine(String.Format("Person Field: Name = {0}, Email = {1}<br></br>", userFieldValue.User.Name, userFieldValue.User.Email));
单用户赋值
item["personfield"] = web.EnsureUser("contoso\\fred");
//or
item["personfield"] = web.EnsureUser("fred@contoso.com");
item.Update();
设置和获取多用户字段
多用户取值
var fieldUserValueCollection = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
s.AppendLine(String.Format("MultiPerson Field: {0}<br></br>", fieldUserValueCollection));
var userCount = 1;
foreach(SPFieldUserValue v in fieldUserValueCollection)
{
s.AppendLine(String.Format("MultiPerson Field, value {0}: {1}<br></br>", userCount, v.User.Name));
userCount++;
}
多用户赋值
var lotsofpeople = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
var personA = web.EnsureUser("contoso\\fred");
var personAValue = new SPFieldUserValue(web, personA.ID, personA.LoginName);
var personB = web.EnsureUser("contoso\\barnie");
var personBValue = new SPFieldUserValue(web, personB.ID, personB.LoginName);
lotsofpeople.Add(personAValue);
lotsofpeople.Add(personBValue);
item["lotsofpeoplefield"] = lotsofpeople;
item.Update();
设置和获取查阅字段
赋值
var lookupField = list.Fields["lookupfield"] as SPFieldLookup;
var lookupList = web.Lists[new Guid(lookupField.LookupList)];
var lookupitem = lookupList.Items[0];
//-or-
//lookupitem = lookupList.GetItemByUniqueId(new Guid("fc71b84c-74d4-4f7c-9eed-fb7a5fbe24a6"));
//-or-
//lookupitem = lookupList.GetItemById(1);
var lookupValue = new SPFieldLookupValue(lookupitem.ID, lookupitem.ID.ToString());
item["lookupfield"] = lookupValue;
item.Update();
取值
var lookupItemValue = new SPFieldLookupValue(item["lookupfield"].ToString());
value = lookupItemValue.LookupValue;
s.AppendLine(String.Format("Lookup Field: {0}<br></br>", value));
设置和获取超链接字段
赋值
var hyperlinkField = list.Fields["hyperlinkfield"] as SPFieldUrl;
var urlFieldValue = new SPFieldUrlValue();
urlFieldValue.Description = "Microsoft";
urlFieldValue.Url = "http://www.microsoft.com ";
//SharePoint 2013 Only
hyperlinkField.ValidateParseAndSetValue(item, urlFieldValue.ToString());
//SharePoint 2010 and SharePoint 2013
hyperlinkField.ParseAndSetValue(item, urlFieldValue.ToString());
item.Update();
取值
var hyperlinkFieldValue = new SPFieldUrlValue(item["hyperlinkfield"].ToString());
value = String.Format("<a href="\"{1}\"">{0}</a>", hyperlinkFieldValue.Description, hyperlinkFieldValue.Url);
s.AppendLine(String.Format("Hyperlink Field: {0}<br></br>", value));
设置和获取托管的元数据字段
赋值
var managedMetaDataField = list.Fields["managedmetadatafield"] as TaxonomyField;
var termsetId = managedMetaDataField.TermSetId;
var termstoreId = managedMetaDataField.SspId;
var taxonomySession = new TaxonomySession(web.Site);
var termstore = taxonomySession.TermStores[termstoreId];
var termset = termstore.GetTermSet(termsetId);
var termname = "Rubbish Tip";
var terms = termset.GetTerms(termname, false);
Term term;
if(terms.Count == 0)
{
term = termset.CreateTerm(termname, termstore.Languages[0]);
termstore.CommitAll();
}
else
{
term = terms[0];
}
managedMetaDataField.SetFieldValue(item, term);
item.Update();
取值
var taxonomyFieldValue = item["managedmetadatafield"] as TaxonomyFieldValue;
s.AppendLine(String.Format("Taxonomy Field: {0} ({1})<br></br>", taxonomyFieldValue.Label, taxonomyFieldValue.TermGuid));
设置和获取值的多个托管元数据字段
多值的托管元数据字段赋值
var managedMetaDataField = list.Fields["managedmetadatafield"] as TaxonomyField;
var termsetId = managedMetaDataField.TermSetId;
var termstoreId = managedMetaDataField.SspId;
var taxonomySession = new TaxonomySession(web.Site);
var termstore = taxonomySession.TermStores[termstoreId];
var termset = termstore.GetTermSet(termsetId);
var multipleManagedMetaDataField = list.Fields["multiplemanagedmetadatafield"] as TaxonomyField;
var termCollection = new TaxonomyFieldValueCollection(multipleManagedMetaDataField);
var taxonomyLabels = new[] {"Frog Catcher", , "Giraffe Stealer" "Moon Dog"};
Term term;
foreach(var label in taxonomyLabels)
{
var terms = termset.GetTerms(label, false);
term = null;
if(terms.Count == 0)
{
term = termset.CreateTerm(label, termstore.Languages[0]);
termstore.CommitAll();
}
else
{
term = terms[0];
}
var termValue = new TaxonomyFieldValue(multipleManagedMetaDataField);
termValue.TermGuid = term.Id.ToString();
termValue.Label = term.Name;
termCollection.Add(termValue);
}
multipleManagedMetaDataField.SetFieldValue(item, termCollection);
item.Update();
多值的托管元数据字段取值
var taxonomyFieldValueCollection = item["multiplemanagedmetadatafield"] as TaxonomyFieldValueCollection;
value = String.Empty;
foreach(var taxonomyValue in taxonomyFieldValueCollection)
{
value = String.IsNullOrEmpty(value)
? String.Format("{0} ({1})", taxonomyValue.Label, taxonomyValue.TermGuid)
: String.Format("{0}, {1} ({2})", value, taxonomyValue.Label, taxonomyValue.TermGuid);
//Or, to use get the term
var currentTerm = termstore.GetTerm(new Guid(taxonomyValue.TermGuid));
//do something with the term
}
s.AppendLine(String.Format("Multiple Taxonomy Field Values: {0})<br></br>", value));
设置和获取计算的字段
- 赋值
计算字段的值是在创建或更新列表项时计算的。它是不可能直接设置此值。可以使用以下方法来设置公式,用以计算字段值。在这些方法之前,有四个主要的属性,可以设置在计算的字段 ;公式、 输出类型、 DisplayFormat 和简写。您需要设置,哪些属性取决于计算值。
公式: 用来计算值的公式。
输出类型: 从计算结果值的类型。受支持的类型,文本、 数字、 整数、 货币、 boolean 类型的值和日期时间。
DisplayFormat: 提供号码、 整数和货币用于指定的小数位数
简写: 与日期时间用于指定日期或日期和时间。
在以下示例中,我们执行以下任务:
- 查看当前的公式
- 查看当前的显示格式
- 从两位小数的显示格式更改为四位小数
- 从货币的输出类型更改为整数
- 更改公式、 输出类型并设置日期格式
//Configuring the calculated field
s.AppendLine(String.Format("Calculated Field Formula: {0}<br></br>", calculatedfield.Formula));
s.AppendLine(String.Format("Calculated Display Format: {0}<br></br>", calculatedfield.DisplayFormat));
s.AppendLine(String.Format("Calculated Output Type: {0}<br></br>", calculatedfield.OutputType));
calculatedfield.DisplayFormat = SPNumberFormatTypes.FourDecimals;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("Calculated Field (Display Format 4 decimals): {0}<br></br>",
calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.OutputType = SPFieldType.Integer;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("Calculated Field (Output Type Integer): {0}<br></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.Formula = "=[datefield]+90";
calculatedfield.DateFormat = SPDateTimeFieldFormatType.DateOnly;
calculatedfield.OutputType = SPFieldType.DateTime;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("Calculated Field (Updated Formula, Date Format and Output Type):{0}<br></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
- 取值
计算的字段的工作方式不同于正常的领域。在列表字段,建立计算公式和时添加或更新列表项,为该列表项的列的值根据计算公式。
获取一个值,计算字段
获取计算的字段的引用。然后获取列表项的引用。最后,调用 GetFieldValueAsText
方法,通过在项目对象计算字段的值。
var calculatedfield = list.Fields["calculatedfield"] as SPFieldCalculated;
value = calculatedfield.GetFieldValueAsText(item["calculatedfield"]);
s.AppendLine(String.Format("Calculated Field: {0}<br></br>", value));