Here’s a control that shows the first non-blank SharePoint field. I created it for Solien’s web site when I added the PageTitle field. By using this control, if content authors leave the PageTitle field blank the contents of the Title field are shown instead.
By inheriting from Microsoft.SharePoint.WebControls.FormComponent we gain access to the Item property.
using System.ComponentModel;
using System.Web.UI.WebControls;
namespace Solien.SharePoint
{
/// <summary>
/// Given a list of fields, displays the first field that has content.
/// </summary>
public class CoalescingFieldControl : Microsoft.SharePoint.WebControls.FormComponent
{
/// <summary>
/// Fields to search for content. Fields are searched in order.
/// </summary>
[TypeConverter(typeof(StringArrayConverter))]
public string[] FieldNames
{
get
{
object o = ViewState["FieldNames"];
if (o == null)
return new string[0];
return (string[])o;
}
set { ViewState["FieldNames"] = value; }
}
protected override void OnPreRender(System.EventArgs e)
{
base.OnPreRender(e);
if (Item != null)
{
foreach (string key in FieldNames)
{
if (Item.Fields.ContainsField(key)
&& Item[key] != null
&& !string.IsNullOrEmpty(Item[key].ToString()))
{
this.Controls.Add(new System.Web.UI.LiteralControl(
Item[key].ToString()));
break;
}
}
}
}
}
}
Because we check that Item.Fields.ContainsField, no exception will be thrown if a field in FieldNames doesn’t exist for the current item.
Here’s how the control is used on a page template:
<%@ Register Tagprefix="SolienSharePointControls" Namespace="Solien.SharePoint "
Assembly="[...]" %>
[…]
<SolienSharePointControls:CoalescingFieldControl id="HomePageTitleInHeader"
FieldNames="PageTitle,Title" runat="server"/>
If you’ve got a SharePoint implementation or asp.net development project you’d like help with, have your people talk to our people.