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.

有帮助吗?

解决方案

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>

其他提示

you can use the onRowDataBound event on the GridView to check the 'M' or "F' and then change the fontcolour depending on the value.

void gridview_RowDataBound(Object sender, GridViewRowEventArgs e)
{

if(e.Row.RowType == DataControlRowType.DataRow)
{
string theValue = e.Row.Cells[3].Text;

if (theValue ="M")
{
e.Row.Cells[1].Forecolor= Color.Red
}

else if (theValue ="F")
{
e.Row.Cells[1].Forecolor= Color.Blue;
}
}
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top