Hannan Ayub
Hannan Ayub

Reputation: 408

How to change a label's color that is present in a repeater on its Onload function?

As the title says, I have a label inside repeater and I want to change its color according to its text value. Is there any way I can do that without mess?

<asp:Label ID="lblVerified" runat="server" Text='<%# Eval("post_verified")%>' OnLoad="lblVerified_Load"

What I want to do is if Eval("post_verified").Equals(Yes) the color should be green and for "NO" it should be red.

Upvotes: 1

Views: 2711

Answers (2)

aguetat
aguetat

Reputation: 514

You can do it by using a conditional operator :

 <asp:Label ID="lblVerified" ForeColor='<%# (Eval("post_verified").Equals("Yes")) ? "Green" : "Red" %>' runat="server" Text='<%# Eval("post_verified")%>' OnLoad="lblVerified_Load">

Worked like a charm with this little edit :

<asp:Label ID="lblVerified" runat="server" Text='<%# Eval("post_verified")%>' ForeColor='<%# (Eval("post_verified").Equals("yes")) ?  System.Drawing.Color.Green : System.Drawing.Color.Red %>'>

Upvotes: 1

Leo
Leo

Reputation: 14830

Assuming that by "inside a repeater" you mean that the label is inside an ItemTemplate or an AlternatingItemTemplate then you should be using the Repeater's ItemDataBound event instead of the label's OnLoad event because the OnLoad event happens too early.

You will need to declare the event handler...

repearter1.ItemDataBound += repearter1_ItemDataBound;

then in the event handler you can find and manipulate the label control...

 void repearter1_ItemDataBound(object sender, RepeaterItemEventArgs e)
 {
            Label lblVerified = e.Item.FindControl("lblVerified") as Label;

            if (lblVerified != null)
            {
                 //TODO: manipulate the control
            }
  }

Notice that you can also get data item from inside the ItemDataBound event if you do the following...

var dataItem = e.Item.DataItem as WhateverTheUnderlyingTypeIs;

Upvotes: 1

Related Questions