Search code examples
c#asp.nettemplatefield

How to set forecolor in TemplateField?


The code below displays either "M" or "F" in the GridView column after evaluating Gender.

        <asp:TemplateField HeaderText="Gender">
            <ItemTemplate>
                <%# Eval("Gender") %>
            </ItemTemplate>
        </asp:TemplateField>

When it's "M" I want to use textcolor red and blue otherwise. How do I do this? Either in the aspx file or in code behind is fine. I'd like to know both ways of doing so if possible.


Solution

  • To do it via markup you'll have to wrap item template content into e.g. <div>, and apply the necessary styles to it like this:

    <asp:TemplateField HeaderText="Gender">
        <ItemTemplate>
            <div style='color: <%# Eval("Gender") == "M" ? "Red" : "Blue" %>'>
                <%# Eval("Gender") %>
            </div>
        </ItemTemplate>
    </asp:TemplateField>