Setting MyLabel.Text in Repeater's HeaderTemplate

Christopher Garcia picture Christopher Garcia · May 21, 2009 · Viewed 12.8k times · Source

Every sample I've found of doing this consists of writing a function outside of my page's OnLoad in order to do this, but I'm curious if there's a more concise way to go about it. I have a Label inside of a HeaderTemplate, and I just want to set the text of the label to a string. I can do the following if the label is outside the repeater:

Month.Text = Enum.GetName(typeof(Month), Convert.ToInt16(MonthList.SelectedValue));

Is there a succinct way to do this?

Answer

Gromer picture Gromer · May 21, 2009

It would be better if you did use the DataBinding event.

ASPX markup:

<asp:Repeater ID="repTest" runat="server">
    <HeaderTemplate>
        <asp:Label ID="lblHeader" runat="server" />
    </HeaderTemplate>
</asp:Repeater>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    repTest.ItemDataBound += new RepeaterItemEventHandler(repTest_ItemDataBound);

    int[] testData = { 1, 2, 3, 4, 5, 6, 7, 8 };
    repTest.DataSource = testData;
    repTest.DataBind();
}

void repTest_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Header)
    {
        Label lblHeader = e.Item.FindControl("lblHeader") as Label;
        if (lblHeader != null)
        {
            lblHeader.Text = "Something";
        }
    }
}

There you go :)