How to set forecolor in TemplateField?
-
29-05-2021 - |
Pregunta
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.
Solución
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>
Otros consejos
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;
}
}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow