I'm building several publishing layouts for a public facing SharePoint 2010 website. One of my page layouts is associated with a content type that has about 20 fields.
I'd like to display all these fields in the format of something like:
<p>Field Name</p>
<p>Field Value</p>
Easy enough to do with the FieldLabel and FieldValue controls:
<asp:Content ContentPlaceholderID="PlaceHolderMain" runat="server">
<SharePointWebControls:FieldLabel id="flSomeField" runat="server" FieldName="SomeField" />
<SharePointWebControls:FieldValue id="fvSomeField" runat="server" FieldName="SomeField" />
</asp:Content>
However, I only want to display the FieldLabel control if the field has a value.
In the code behind of the page layout, I do the following as part of page load:
var listItem = SPContext.Current.ListItem;
if (listItem != null)
{
var someField = String.Empty;
if (listItem.TryGetValue<string>("SomeField", out someField))
if (String.IsNullOrEmpty(someField))
// Find the control and set its visibility
}
I'm having a hard time finding the FieldLabel control.
I wrote a recursive extension method:
public static T FindControl<T>(this ControlCollection controls, string id) where T : Control
{
T found = default(T);
if (controls != null && controls.Count > 0)
{
for (int i = 0; i < controls.Count; i++)
{
if (controls[i] is T && controls[i].ID.Equals(id, StringComparison.InvariantCultureIgnoreCase))
{
found = controls[i] as T;
break;
}
else
found = FindControl<T>(controls[i].Controls, id);
}
}
return found;
}
which I call like this:
var flSomeField = this.Controls.FindControl<FieldLabel>("flSomeField");
but it's a recursive mess to say the least...
Any thoughts on how best to do this, or is there another approach I should consider?