Question

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?

Was it helpful?

Solution

Try adding the member variable:

public class XYX : PublishingLayoutPage {
    protected FieldLabel flSomeField;
}

And ASP.NET should auto-wire it up. Then you can use:

flSomeField.DoStuff();

That is if the naming container is in scope

OTHER TIPS

You should be able to access the controls from your code-behind using:

this.flSomeField

Maybe the problem is in the definition of your code-behind class or in the reference to your code file in the Page directive.

Try inserting your OnLoad method inside a script tag in your .aspx file instead of your code-behind file, just to verify that your controls are accessible.

You can access it from the sharepoint not from the page itself like this

Microsoft.SharePoint.SPContext.Current.ListItem["FieldName"]

and if you need the field itself not the value

Microsoft.SharePoint.SPContext.Current.ListItem.Fields["FieldName"]
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top