简体   繁体   English

如何在 TemplateField 中设置前景色?

[英]How to set forecolor in TemplateField?

The code below displays either "M" or "F" in the GridView column after evaluating Gender.下面的代码在评估性别后在 GridView 列中显示“M”或“F”。

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

When it's "M" I want to use textcolor red and blue otherwise.当它是“M”时,我想使用文本颜色红色和蓝色。 How do I do this?我该怎么做呢? Either in the aspx file or in code behind is fine.无论是在 aspx 文件中还是在后面的代码中都可以。 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 eg <div> , and apply the necessary styles to it like this:要通过标记来做到这一点,您必须将项目模板内容包装到例如<div>中,并像这样将必要的 styles 应用于它:

<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.您可以使用 GridView 上的onRowDataBound事件来检查“M”或“F”,然后根据值更改字体颜色。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM