SharePoint: 史上最全c#设置和获取Fields

适用环境

  • SharePoint 2010
  • SharePoint 2013

Get the List, and the first SPListItem

var web = SPContext.Current.Site.RootWeb;
var list = web.Lists.TryGetList("fieldslist");
if (list == null) return;
//Get Item 1, or add a new item if the list doesn't contain any items
SPListItem item;
item = list.ItemCount > 0 ? list.Items[0] : list.Items.Add();

Set and Get the Title

//Set the Title
item["Title"] = String.Format("Title updated at {0}",t);
//Get the Title
value = item["Title"].ToString();

Set and Get a Text Field

//set
item["textfield"] = String.Format("At {0} dogs still can't write poems", t);
item.Update();
//get
value = item["textfield"].ToString();

Set and Get a Note (or RichText) Field

//set
item["notefield"] = String.Format("At {0} dogs still can't write poems. \r\nBut then, neither can I!", t);
item.Update();
//get
value = item["notefield"].ToString();
s.AppendLine(String.Format("<span>Note Field: {0}</span></br>", value));

Set and Get a Yes/No Field (Boolean)

//set
item["yesnofield"] = false;
item.Update();
//get
value = item["yesnofield"].ToString();

Set and Get a Number Field

//set
item["numberfield"] = 35;
item["numberfield"] = Double.Parse("354.67");
item.Update();
//get
value = item["numberfield"].ToString();
value = Double.Parse(item["numberfield"].ToString()).ToString("F1");
value = Double.Parse(item["numberfield"].ToString()).ToString("F0");

Set and Get a Date Field

//set
item["datefield"] = DateTime.Now;
  //Or, set the date to Now + two days
item["datefield"] = DateTime.Now.AddDays(2);
item.Update();
//get
value = item["datefield"].ToString();
value = DateTime.Parse(item["datefield"].ToString()).ToString("d");
value = DateTime.Parse(item["datefield"].ToString()).ToString("D");
value = DateTime.Parse(item["datefield"].ToString()).ToString("R");
var dateValue = DateTime.Parse(item["datefield"].ToString());
value = dateValue.AddDays(13).ToString("dd-MMM-yy");

Set and Get a Choice Field

//set
var choicevalues = new SPFieldMultiChoiceValue();
choicevalues.Add("Green");
choicevalues.Add("Blue");
item["multiplechoicefield"] = choicevalues;
item.Update();
//get
list.Fields["multiplechoicefield"].ParseAndSetValue(item, choicevalues.ToString());
var multipleChoiceValues = new SPFieldMultiChoiceValue(item["multiplechoicefield"].ToString());
s.AppendLine(String.Format("<span>Multiple Choice Field: {0}</span></br>", multipleChoiceValues));
for (int i = 0; i <= multipleChoiceValues.Count - 1; i++)
{
    s.AppendLine(String.Format("<span>Multiple Choice Field, value {0}: {1}</span></br>", i, multipleChoiceValues[i]));
}

Set and Get a Person Field

//set
item["personfield"] = web.EnsureUser("contoso\\fred");
  //or
item["personfield"] = web.EnsureUser("fred@contoso.com");
item.Update();
//get
value = item["personfield"].ToString();
s.AppendLine(String.Format("<span>Person Field: {0}</span></br>", value));
var userFieldValue = new SPFieldUserValue(web, item["personfield"].ToString());
s.AppendLine(String.Format("<span>Person Field: Name = {0}, Email = {1}</span></br>", userFieldValue.User.Name, userFieldValue.User.Email));

Set and Get a Multi-Person Field

//set
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();

//get
var fieldUserValueCollection = new SPFieldUserValueCollection(web, item["lotsofpeoplefield"].ToString());
s.AppendLine(String.Format("<span>MultiPerson Field: {0}</span></br>", fieldUserValueCollection));
var userCount = 1;
foreach (SPFieldUserValue v in fieldUserValueCollection)
{
    s.AppendLine(String.Format("<span>MultiPerson Field, value {0}: {1}</span></br>", userCount, v.User.Name));
    userCount++;
}

Set and Get a Lookup Field

//set
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();

//get
var lookupItemValue = new SPFieldLookupValue(item["lookupfield"].ToString());
value = lookupItemValue.LookupValue;

Setting and Getting a HyperLink Field

//set
var hyperlinkField = list.Fields["hyperlinkfield"] as SPFieldUrl;
var urlFieldValue = new SPFieldUrlValue();
urlFieldValue.Description = "Microsoft";
urlFieldValue.Url = "http://www.microsoft.com This link is external to TechNet Wiki. It will open in a new window. ";
//SharePoint 2013 Only
hyperlinkField.ValidateParseAndSetValue(item, urlFieldValue.ToString());
//SharePoint 2010 and SharePoint 2013
hyperlinkField.ParseAndSetValue(item, urlFieldValue.ToString());
item.Update();

//get
var hyperlinkFieldValue = new SPFieldUrlValue(item["hyperlinkfield"].ToString());
value = String.Format("<a href=\"{1}\" alt=\"{0}\">{0}</a>", hyperlinkFieldValue.Description, hyperlinkFieldValue.Url);

Setting and Getting a Managed Metadata Field

//set
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();

//get
var taxonomyFieldValue = item["managedmetadatafield"] as TaxonomyFieldValue;
s.AppendLine(String.Format("<span>Taxonomy Field: {0} ({1})</span></br>", taxonomyFieldValue.Label, taxonomyFieldValue.TermGuid));

Setting and Getting a Multiple Valued Managed Metadata Field

//set
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();

//get
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
}

See Also
A Complete Guide to Getting and Setting Fields using PowerShell
SPField
SPFieldText
SPFieldMultiLineText (Note)
SPFieldBoolean
SPFieldCalculated
SPFieldChoice
SPFieldCurrency
SPFieldDateTime
SPFieldLookup
SPFieldMultiChoice
SPFieldMultiChoiceValue
SPFieldNumber
SPFieldUrl
SPFieldUserValue
SPFieldUserValueCollection
SPNumberFormatTypes
SPFieldType
SPDateTimeFieldFormatType

原文链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值