2012-04-06 35 views
1

評估性別後,下面的代碼在GridView列中顯示「M」或「F」。如何在TemplateField中設置forecolor?

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

當它的 「M」 我想使用的文字顏色紅色和藍色,否則。我該怎麼做呢?無論是在aspx文件或在後面的代碼是好的。如果可能,我想知道這兩種方法。

回答

2

要通過標記你就必須這樣做將項目模板內容包裝成例如<div>,並將其應用於如下所需的樣式:

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

可以使用在GridView中onRowDataBound事件來檢查「M」或「F」,然後改變取決於價值fontcolour。

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; 
} 
} 
} 
相關問題