Question

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?

Was it helpful?

Solution

Try the following inside your header template:

<asp:Label ID="Month" runat="server" Text='<%# (Month)Convert.ToInt16(MonthList.SelectedValue) %>' />

OTHER TIPS

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 :)

I'm not 100% certain whether or not you need to wait for the Repeater to have data bound to it or not, but this is how you would access a control within it's header:

var myLabel = MyRepeater.Controls[0].Controls[0].FindControl("MyLabel") as Label;
myLabel.Text = "Hello World";

You should probably break that into multiple lines and check to make sure that there is an object at Controls[0].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top