Rendering Display/Html Values for SharePoint List Items
I see this all the time in the forums, and rather than just reply to the thread over and over again with the same content, I’m just going to provide some implementation details here.
Every SPField class in SharePoint implements a method for rendering a value of that particular field to html and/or display. This functionality is implemented using methods (GetFieldValueAsHtml and GetFieldValueAsText) found in the base SPField class, and every class that inherits SPField in the SharePoint APIs. Because these methods are marked as virtual on the SPField class, the runtime will always execute the lowest level of inheritance for child classes. (So, since SPFieldDateTime inherits SPField, if it overrides GetFieldValueAsHtml , and you call SPField.GetFieldValueAsHtml, it will call the implementation found in the SPFieldDateTime class.
Usage of these methods is very simple: you pass a reference to field on a specific SPListItem, and it spits back a string with the appropriate display output. This is an extremely valuable pattern when you are trying to render values from SharePoint Lists in custom web parts and application pages.
Take, for example, the following console application. It works with a DateTime field on a Tasks list (Due Date) and a calculated column that I created (DueDatePlus5) that simply adds 5 to the Due Date.
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite(@"http://dev/"))
{
using (SPWeb web = site.OpenWeb())
{
// get the list
SPList taskList = web.Lists["Tasks"];
SPListItem item = taskList.GetItemById(1);
Output(item, "Due Date");
Console.WriteLine();
Output(item, "DueDatePlus5");
Console.ReadLine();
}
}
}
static void Output(SPListItem Item, string ColumnDisplayName)
{
// get the field
SPField field = Item.Fields[ColumnDisplayName];
object value = Item[field.Id];
Console.WriteLine(@"To String: " + value.ToString());
Console.WriteLine(@"GetFieldValueAsHtml: " + field.GetFieldValueAsHtml(value));
Console.WriteLine(@"GetFieldValueAsText: " + field.GetFieldValueAsText(value));
}
}
Here is the output that the program spits out:
To String: 2/25/2010 12:00:00 AM
GetFieldValueAsHtml: 2/24/2010
GetFieldValueAsText: 2/24/2010
To String: datetime;#2010-03-02 00:00:00
GetFieldValueAsHtml: 3/1/2010
GetFieldValueAsText: 3/1/2010
Notice how it formats the data nicely for rendering inside of a web page, particularly for the calculated column. MUCH easier than parsing out the string value.