Retrocoder
Retrocoder

Reputation: 4713

Setting asp:label text colour based on text

I am databinding a gridview and one of the columns is defined as shown below. What I would like to do is to colour the text depending on whether the text says "Yes" or "No". If the text is "Yes" I'd like to set it to red else set it to green. Can this be done and if so should it be done via css or can I add some code to the line?

<asp:TemplateField HeaderText="Validated" ItemStyle-HorizontalAlign="Center" SortExpression="Product">
    <ItemTemplate>
        <asp:Label ID="lblValidated" runat="server" Text='<%# Bind("Validation") %>' />
    </ItemTemplate>
</asp:TemplateField>

Upvotes: 1

Views: 1091

Answers (1)

A. Agius
A. Agius

Reputation: 1271

The below should do what you want.

ASP.NET

<asp:TemplateField HeaderText="Validated" ItemStyle-HorizontalAlign="Center" SortExpression="Product">
<ItemTemplate>
    <asp:Label ID="lblValidated" runat="server" Text='<%# Bind("Validation") %>' CssClass='<%# SetColor(DataBinder.Eval(Container.DataItem, "Validation")) %>'  />
</ItemTemplate>

C#

public string SetColor(string Text)
{
    return Text.ToUpper == "YES" ? "GreenClass" : "RedClass"
}

CSS

.GreenClass{color:green;}
.RedClass{color:red;}

Upvotes: 3

Related Questions