SharePoint 2013 | SharePoint 2010 |
What is SharePoint 2013 (Preview) – A new version of Microsoft famous Collaboration portal called SharePoint. The version adds few new exciting features such as Social Feed,SharePoint Apps and cross-site publishing. | What is SharePoint 2010 – It is a previous or I should say current version of SharePoint that was released in year 2010. |
Development Changes –
| Development Changes –
|
Social and Collaboration features – Microsoft in SharePoint 2013 Introduced new Social capabilities for better collaboration in the company.New Features added are –
| Social and Collaboration features –SharePoint 2010 had very few social capabilities.
|
Search – SharePoint 2013 includes several enhancements, custom content processing with the Content Enrichment web service, and a new framework for presenting search result types. Some of the features added are –
| Search – SharePoint 2010 had Introduced Integrated FAST search as an Enterprise search. In addition to this build-in SharePoint search is still widely used in companies. |
Enterprise Content Management (ECM) – SharePoint 2013 added some of the best capabilities of an ECM software. The newly added stuff is
| Enterprise Content Management (ECM) –SharePoint 2010 on the other hand had Introduced Managed metadata and taxonomy as a part of new ECM benefits for SP 2010. This version did not had Managed Navigation and Cross-site Publishing. SharePoint designer was a primary tool to modify Master pages instead of the new Design Manager. |
Search This Blog
Saturday, October 22, 2016
Sharepoint 2013 Vs Sharepoint 2010
Thursday, October 20, 2016
Export SPGridView to Excel spreadsheet in Sharepoint 2013
using System;
using System.IO;
using System.Web;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace ExportGridtoExcel
{
[Guid("2fa65763-1ef1-4173-8a77-685e840f0196")]
public class ExportGridtoExcel : System.Web.UI.WebControls.WebParts.WebPart
{
SPGridView myGridView;
SPDataSource myDataSource = new SPDataSource();
Button oBtn_Export;
protected override void CreateChildControls()
{
oBtn_Export = new Button();
oBtn_Export.Text = "Export to Excel";
oBtn_Export.CssClass = "ButtonHeightWidth";
oBtn_Export.Click += new EventHandler(oBtn_Export_Click);
this.Controls.Add(oBtn_Export);
myGridView = new SPGridView();
myGridView.Enabled = true;
myGridView.AutoGenerateColumns = false;
SPBoundField colTitle = new SPBoundField();
colTitle.DataField = "Country";
colTitle.HeaderText = "Country";
this.myGridView.Columns.Add(colTitle);
SPBoundField colMission = new SPBoundField();
colMission.DataField = "State";
colMission.HeaderText = "State";
this.myGridView.Columns.Add(colMission);
this.Controls.Add(myGridView);
}
void oBtn_Export_Click(object sender, EventArgs e)
{
ExportToExcel("CountryState.xls", myGridView);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = SPContext.Current.Web;
SPList list = myWeb.Lists["Countries"];
myDataSource.List = list;
myGridView.DataSource = myDataSource;
myGridView.DataBind();
}
public static void ExportToExcel(string strFileName, SPGridView gv)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition",
string.Format("attachment; filename={0}", strFileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
}
}
using System.IO;
using System.Web;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace ExportGridtoExcel
{
[Guid("2fa65763-1ef1-4173-8a77-685e840f0196")]
public class ExportGridtoExcel : System.Web.UI.WebControls.WebParts.WebPart
{
SPGridView myGridView;
SPDataSource myDataSource = new SPDataSource();
Button oBtn_Export;
protected override void CreateChildControls()
{
oBtn_Export = new Button();
oBtn_Export.Text = "Export to Excel";
oBtn_Export.CssClass = "ButtonHeightWidth";
oBtn_Export.Click += new EventHandler(oBtn_Export_Click);
this.Controls.Add(oBtn_Export);
myGridView = new SPGridView();
myGridView.Enabled = true;
myGridView.AutoGenerateColumns = false;
SPBoundField colTitle = new SPBoundField();
colTitle.DataField = "Country";
colTitle.HeaderText = "Country";
this.myGridView.Columns.Add(colTitle);
SPBoundField colMission = new SPBoundField();
colMission.DataField = "State";
colMission.HeaderText = "State";
this.myGridView.Columns.Add(colMission);
this.Controls.Add(myGridView);
}
void oBtn_Export_Click(object sender, EventArgs e)
{
ExportToExcel("CountryState.xls", myGridView);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = SPContext.Current.Web;
SPList list = myWeb.Lists["Countries"];
myDataSource.List = list;
myGridView.DataSource = myDataSource;
myGridView.DataBind();
}
public static void ExportToExcel(string strFileName, SPGridView gv)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition",
string.Format("attachment; filename={0}", strFileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
private static void PrepareControlForExport(Control control)
{
for (int i = 0; i < control.Controls.Count; i++)
{
Control current = control.Controls[i];
if (current is LinkButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
}
else if (current is ImageButton)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
}
else if (current is HyperLink)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
}
else if (current is DropDownList)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
}
else if (current is CheckBox)
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
}
if (current.HasControls())
{
PrepareControlForExport(current);
}
}
}
}
}
A Quick Guide to Getting and Setting the various SPField types using C#
Introduction
This article demonstrates how to set and get the various SPField types for a SharePoint list using C#.
The examples demonstrated set and get fields from an item that belongs to a custom list. The custom list contains a number of fields, and all the fields are named based on the type of field they are. For example, there is a Text field, which has been named, textfield. This is depicted in the following picture:
Applies To
The examples demonstrated below are tested with and apply to the following versions of SharePoint:
SharePoint 2010
SharePoint 2013
Get the List, and the first SPListItem
This is the basic code for getting an item. If the list has at least one item, the first item is retrieved, otherwise a new item is created.
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();
Create Variables used in the Examples
//Date of current update
var t = DateTime.Now.ToLongTimeString();
//StringBuilder for output
var s = new StringBuilder();
//Variable for storing temporary values
String value;
Set and Get the Title
Set the title
//Set the Title
item["Title"] = String.Format("Title updated at {0}",t);
Get the title
value = item["Title"].ToString();
s.AppendLine(String.Format("<span>Title Field: {0}</span></br>", value));
Set and Get a Text Field
Set a text field
item["textfield"] = String.Format("At {0} dogs still can't write poems", t);
item.Update();
Get a text field
value = item["textfield"].ToString();
s.AppendLine(String.Format("<span>Text Field: {0}</span></br>", value));
Set and Get a Note (or RichText) Field
Set a note field
item["notefield"] = String.Format("At {0} dogs still can't write poems. \r\nBut then, neither can I!", t);
item.Update();
Get a note field
value = item["notefield"].ToString();
s.AppendLine(String.Format("<span>Note Field: {0}</span></br>", value));
Set and Get a Yes/No Field (Boolean)
Set a yes/no field
item["yesnofield"] = false;
item.Update();
Get a yes/no field
value = item["yesnofield"].ToString();
s.AppendLine(String.Format("<span>Yes/No Field: {0}</span></br>", value));
Set and Get a Number Field
The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display. See Double.ToString for more information.
Set a number field
item["numberfield"] = 35;
//Or
item["numberfield"] = Double.Parse("354.67");
item.Update();
Get a number field
value = item["numberfield"].ToString();
s.AppendLine(String.Format("<span>Number Field: {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F1");
s.AppendLine(String.Format("<span>Number Field (one decimal place): {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F0");
s.AppendLine(String.Format("<span>Number Field (two decimal places): {0}</span></br>", value));
Set and Get a Currency (Number) Field
A currency field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a currency. See Double.ToString for more information.
Set a currency field
item["currencyfield"] = Double.Parse("354.67");
item.Update();
Get a currency field
value = item["currencyfield"].ToString();
s.AppendLine(String.Format("<span>Currency Field: {0}</span></br>", value));
value = Double.Parse(item["currencyfield"].ToString()).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (formatted as a currency): {0}</span></br>", value));
value = (Double.Parse(item["numberfield"].ToString()) + 123).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (addition): {0}</span></br>", value));
Set and Get a Percent (Number) Field
A percentage field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a percentage. See Double.ToString for more information.
Set a percent field
item["percentfield"] = Double.Parse("0.8735");
item.Update();
Get a percent field
value = item["percentfield"].ToString();
s.AppendLine(String.Format("<span>Percent Field: {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P0");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, and as a whole number): {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P2");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, with two decimal places): {0}</span></br>", value));
Set and Get a Date Field
To set a date field, use a System.DateTime object to create a date, then assign the DateTime object to the list item's field. When you retrieve the value of a DateTime field, you can use standard date format specifiers to format the output of the value. See DateTime.ToString for more information.
Set a date field
item["datefield"] = DateTime.Now;
//Or, set the date to Now + two days
item["datefield"] = DateTime.Now.AddDays(2);
item.Update();
Get a date field
value = item["datefield"].ToString();
s.AppendLine(String.Format("<span>Date Field: {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("d");
s.AppendLine(String.Format("<span>Date Field (using the \"6/15/2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("D");
s.AppendLine(String.Format("<span>Date Field (using the \"Sunday, June 15, 2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("R");
s.AppendLine(String.Format("<span>Date Field (using the \"Sun, 15 Jun 2008 21:15:07 GMT\" format): {0}</span></br>", value));
var dateValue = DateTime.Parse(item["datefield"].ToString());
value = dateValue.AddDays(13).ToString("dd-MMM-yy");
s.AppendLine(String.Format("<span>Date Field (using a custom display format): {0}</span></br>", value));
Set and Get a Choice Field
Set a choice field
item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Green");
item.Update();
//Or, to add a new value
var choiceField = list.Fields["choicefield"] as SPFieldChoice;
if (!choiceField.Choices.Contains("Aquamarine"))
{
choiceField.AddChoice("Aquamarine");
choiceField.Update();
}
item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Aquamarine");
item.Update();
Get a choice field
value = item["choicefield"].ToString();
s.AppendLine(String.Format("<span>Choice Field: {0}</span></br>", value));
Set and Get a Multi-Choice Field
Set a multi-choice field
var choicevalues = new SPFieldMultiChoiceValue();
choicevalues.Add("Green");
choicevalues.Add("Blue");
item["multiplechoicefield"] = choicevalues;
item.Update();
Get a multi-choice field
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 a person field
item["personfield"] = web.EnsureUser("contoso\\fred");
//or
item["personfield"] = web.EnsureUser("fred@contoso.com");
item.Update();
Get a person field
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 a multi-person field
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 a multi-person field
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 a lookup field
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 a lookup field
var lookupItemValue = new SPFieldLookupValue(item["lookupfield"].ToString());
value = lookupItemValue.LookupValue;
s.AppendLine(String.Format("<span>Lookup Field: {0}</span></br>", value));
Setting and Getting a HyperLink Field
Set a hyperlink field
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();
Get a hyperlink field
var hyperlinkFieldValue = new SPFieldUrlValue(item["hyperlinkfield"].ToString());
value = String.Format("<a href=\"{1}\" alt=\"{0}\">{0}</a>", hyperlinkFieldValue.Description, hyperlinkFieldValue.Url);
s.AppendLine(String.Format("<span>Hyperlink Field: {0}</span></br>", value));
Setting and Getting a Managed Metadata Field
Set a Managed Metadata field
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 a Managed Metadata field
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 a Multiple Valued Managed Metadata field
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 a Multiple Valued Managed Metadata field
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("<span>Multiple Taxonomy Field Values: {0})</span></br>", value));
Setting and Getting a Calculated Field
Calculated fields work in a different manner to that of normal fields. A formula is set on the list field, and when a list item is added or updated, the value of the column for that list item is calculated based on the formula.
Get a Calculated Field value
Get a reference to the calculated field. Then get a reference to the list item. Finally, call the GetFieldValueAsText method, passing in the value of the item objects calculated field.
var calculatedfield = list.Fields["calculatedfield"] as SPFieldCalculated;
value = calculatedfield.GetFieldValueAsText(item["calculatedfield"]);
s.AppendLine(String.Format("<span>Calculated Field: {0}</span></br>", value));
Set the Properties of a Calculated Field
The value of a calculated field is calculated at the time a list item is created or updated. It is not possible to directly set this value. You can use the following methods to set the formula though, which is used to calculate the fields value. Before looking at these methods, there are four main properties that can be set on a calculated field; Formula, OutputType, DisplayFormat and DateFormat. Which properties you need to set, depends on the value of the calculation.
Formula: The formula used to calculate the value.
OutputType: The type of the value that results from the calculation. Supported types are, Text, Number, Integer, Currency, Boolean and DateTime.
DisplayFormat: Used with number, integer and currency to specify the number of decimal places
DateFormat: Used with DateTime to specify Date, or Date and Time.
In the following example, we perform the following tasks:
View the current formula
View the current display format
Change the display format from two decimal places to four decimal places
Change the output type from currency to integer
Change the formula, output type and set the date format
//Configuring the calculated field
s.AppendLine(String.Format("<span>Calculated Field Formula: {0}</span></br>", calculatedfield.Formula));
s.AppendLine(String.Format("<span>Calculated Display Format: {0}</span></br>", calculatedfield.DisplayFormat));
s.AppendLine(String.Format("<span>Calculated Output Type: {0}</span></br>", calculatedfield.OutputType));
calculatedfield.DisplayFormat = SPNumberFormatTypes.FourDecimals;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Display Format 4 decimals): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.OutputType = SPFieldType.Integer;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Output Type Integer): {0}</span></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("<span>Calculated Field (Updated Formula, Date Format and Output Type): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
This article demonstrates how to set and get the various SPField types for a SharePoint list using C#.
The examples demonstrated set and get fields from an item that belongs to a custom list. The custom list contains a number of fields, and all the fields are named based on the type of field they are. For example, there is a Text field, which has been named, textfield. This is depicted in the following picture:
Applies To
The examples demonstrated below are tested with and apply to the following versions of SharePoint:
SharePoint 2010
SharePoint 2013
Get the List, and the first SPListItem
This is the basic code for getting an item. If the list has at least one item, the first item is retrieved, otherwise a new item is created.
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();
Create Variables used in the Examples
//Date of current update
var t = DateTime.Now.ToLongTimeString();
//StringBuilder for output
var s = new StringBuilder();
//Variable for storing temporary values
String value;
Set and Get the Title
Set the title
//Set the Title
item["Title"] = String.Format("Title updated at {0}",t);
Get the title
value = item["Title"].ToString();
s.AppendLine(String.Format("<span>Title Field: {0}</span></br>", value));
Set and Get a Text Field
Set a text field
item["textfield"] = String.Format("At {0} dogs still can't write poems", t);
item.Update();
Get a text field
value = item["textfield"].ToString();
s.AppendLine(String.Format("<span>Text Field: {0}</span></br>", value));
Set and Get a Note (or RichText) Field
Set a note field
item["notefield"] = String.Format("At {0} dogs still can't write poems. \r\nBut then, neither can I!", t);
item.Update();
Get a note field
value = item["notefield"].ToString();
s.AppendLine(String.Format("<span>Note Field: {0}</span></br>", value));
Set and Get a Yes/No Field (Boolean)
Set a yes/no field
item["yesnofield"] = false;
item.Update();
Get a yes/no field
value = item["yesnofield"].ToString();
s.AppendLine(String.Format("<span>Yes/No Field: {0}</span></br>", value));
Set and Get a Number Field
The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display. See Double.ToString for more information.
Set a number field
item["numberfield"] = 35;
//Or
item["numberfield"] = Double.Parse("354.67");
item.Update();
Get a number field
value = item["numberfield"].ToString();
s.AppendLine(String.Format("<span>Number Field: {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F1");
s.AppendLine(String.Format("<span>Number Field (one decimal place): {0}</span></br>", value));
value = Double.Parse(item["numberfield"].ToString()).ToString("F0");
s.AppendLine(String.Format("<span>Number Field (two decimal places): {0}</span></br>", value));
Set and Get a Currency (Number) Field
A currency field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a currency. See Double.ToString for more information.
Set a currency field
item["currencyfield"] = Double.Parse("354.67");
item.Update();
Get a currency field
value = item["currencyfield"].ToString();
s.AppendLine(String.Format("<span>Currency Field: {0}</span></br>", value));
value = Double.Parse(item["currencyfield"].ToString()).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (formatted as a currency): {0}</span></br>", value));
value = (Double.Parse(item["numberfield"].ToString()) + 123).ToString("C2");
s.AppendLine(String.Format("<span>Currency Field (addition): {0}</span></br>", value));
Set and Get a Percent (Number) Field
A percentage field uses the same SharePoint field type as Number (SPFieldNumber). The type of a Number field is a Double. When you get the number from the field, you can use standard numeric format specifies to format the number for display, specifically, formatting it as a percentage. See Double.ToString for more information.
Set a percent field
item["percentfield"] = Double.Parse("0.8735");
item.Update();
Get a percent field
value = item["percentfield"].ToString();
s.AppendLine(String.Format("<span>Percent Field: {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P0");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, and as a whole number): {0}</span></br>", value));
value = Double.Parse(item["percentfield"].ToString()).ToString("P2");
s.AppendLine(String.Format("<span>Percent Field (formatted as a percent, with two decimal places): {0}</span></br>", value));
Set and Get a Date Field
To set a date field, use a System.DateTime object to create a date, then assign the DateTime object to the list item's field. When you retrieve the value of a DateTime field, you can use standard date format specifiers to format the output of the value. See DateTime.ToString for more information.
Set a date field
item["datefield"] = DateTime.Now;
//Or, set the date to Now + two days
item["datefield"] = DateTime.Now.AddDays(2);
item.Update();
Get a date field
value = item["datefield"].ToString();
s.AppendLine(String.Format("<span>Date Field: {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("d");
s.AppendLine(String.Format("<span>Date Field (using the \"6/15/2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("D");
s.AppendLine(String.Format("<span>Date Field (using the \"Sunday, June 15, 2008\" format): {0}</span></br>", value));
value = DateTime.Parse(item["datefield"].ToString()).ToString("R");
s.AppendLine(String.Format("<span>Date Field (using the \"Sun, 15 Jun 2008 21:15:07 GMT\" format): {0}</span></br>", value));
var dateValue = DateTime.Parse(item["datefield"].ToString());
value = dateValue.AddDays(13).ToString("dd-MMM-yy");
s.AppendLine(String.Format("<span>Date Field (using a custom display format): {0}</span></br>", value));
Set and Get a Choice Field
Set a choice field
item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Green");
item.Update();
//Or, to add a new value
var choiceField = list.Fields["choicefield"] as SPFieldChoice;
if (!choiceField.Choices.Contains("Aquamarine"))
{
choiceField.AddChoice("Aquamarine");
choiceField.Update();
}
item["choicefield"] = list.Fields["choicefield"].GetFieldValue("Aquamarine");
item.Update();
Get a choice field
value = item["choicefield"].ToString();
s.AppendLine(String.Format("<span>Choice Field: {0}</span></br>", value));
Set and Get a Multi-Choice Field
Set a multi-choice field
var choicevalues = new SPFieldMultiChoiceValue();
choicevalues.Add("Green");
choicevalues.Add("Blue");
item["multiplechoicefield"] = choicevalues;
item.Update();
Get a multi-choice field
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 a person field
item["personfield"] = web.EnsureUser("contoso\\fred");
//or
item["personfield"] = web.EnsureUser("fred@contoso.com");
item.Update();
Get a person field
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 a multi-person field
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 a multi-person field
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 a lookup field
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 a lookup field
var lookupItemValue = new SPFieldLookupValue(item["lookupfield"].ToString());
value = lookupItemValue.LookupValue;
s.AppendLine(String.Format("<span>Lookup Field: {0}</span></br>", value));
Setting and Getting a HyperLink Field
Set a hyperlink field
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();
Get a hyperlink field
var hyperlinkFieldValue = new SPFieldUrlValue(item["hyperlinkfield"].ToString());
value = String.Format("<a href=\"{1}\" alt=\"{0}\">{0}</a>", hyperlinkFieldValue.Description, hyperlinkFieldValue.Url);
s.AppendLine(String.Format("<span>Hyperlink Field: {0}</span></br>", value));
Setting and Getting a Managed Metadata Field
Set a Managed Metadata field
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 a Managed Metadata field
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 a Multiple Valued Managed Metadata field
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 a Multiple Valued Managed Metadata field
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("<span>Multiple Taxonomy Field Values: {0})</span></br>", value));
Setting and Getting a Calculated Field
Calculated fields work in a different manner to that of normal fields. A formula is set on the list field, and when a list item is added or updated, the value of the column for that list item is calculated based on the formula.
Get a Calculated Field value
Get a reference to the calculated field. Then get a reference to the list item. Finally, call the GetFieldValueAsText method, passing in the value of the item objects calculated field.
var calculatedfield = list.Fields["calculatedfield"] as SPFieldCalculated;
value = calculatedfield.GetFieldValueAsText(item["calculatedfield"]);
s.AppendLine(String.Format("<span>Calculated Field: {0}</span></br>", value));
Set the Properties of a Calculated Field
The value of a calculated field is calculated at the time a list item is created or updated. It is not possible to directly set this value. You can use the following methods to set the formula though, which is used to calculate the fields value. Before looking at these methods, there are four main properties that can be set on a calculated field; Formula, OutputType, DisplayFormat and DateFormat. Which properties you need to set, depends on the value of the calculation.
Formula: The formula used to calculate the value.
OutputType: The type of the value that results from the calculation. Supported types are, Text, Number, Integer, Currency, Boolean and DateTime.
DisplayFormat: Used with number, integer and currency to specify the number of decimal places
DateFormat: Used with DateTime to specify Date, or Date and Time.
In the following example, we perform the following tasks:
View the current formula
View the current display format
Change the display format from two decimal places to four decimal places
Change the output type from currency to integer
Change the formula, output type and set the date format
//Configuring the calculated field
s.AppendLine(String.Format("<span>Calculated Field Formula: {0}</span></br>", calculatedfield.Formula));
s.AppendLine(String.Format("<span>Calculated Display Format: {0}</span></br>", calculatedfield.DisplayFormat));
s.AppendLine(String.Format("<span>Calculated Output Type: {0}</span></br>", calculatedfield.OutputType));
calculatedfield.DisplayFormat = SPNumberFormatTypes.FourDecimals;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Display Format 4 decimals): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
calculatedfield.OutputType = SPFieldType.Integer;
calculatedfield.Update();
item.Update();
s.AppendLine(String.Format("<span>Calculated Field (Output Type Integer): {0}</span></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("<span>Calculated Field (Updated Formula, Date Format and Output Type): {0}</span></br>", calculatedfield.GetFieldValueAsText(item["calculatedfield"])));
Subscribe to:
Posts (Atom)