2014-01-21 87 views
2

我想更改一些特殊單詞的顏色並非gridview單元格中的所有單詞。 下面是代碼:在gridview單元格中更改forecolor af特殊單詞

protected void gvContents_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     if (e.Row.Cells[3].Text.Contains("Special")) 
     { 
      //set The "Special" word only forecolor to red 
     } 
     else if (e.Row.Cells[3].Text == "Perishable") 
     { 
      //set The "Perishable" word only forecolor to blue 
     } 
     else if (e.Row.Cells[3].Text == "Danger") 
     { 
      //set The "Danger" word only forecolor to yellow 
     } 
    } 
} 

和單元格文本可能會像在這裏:Radioactive : Danger或本:Human Body : Special ,Perishable。我該怎麼辦?

回答

2

使用span tags和CSS類的組合。

<style> 
    .redWord 
    { 
     color: Red; 
    } 
    .blueWord 
    { 
     color: Blue; 
    } 
    .yellowWord 
    { 
     color: Yellow; 
    } 
</style> 

然後替換的Special所有出現到<span class='redWord'>Special</span>Perishable<span class='blueWord'>Perishable</span>,並Danger<span class='yellowWord'>Danger</span>

protected void gvContents_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     e.Row.Cells[3].Text = e.Row.Cells[3].Text.Replace("Special", "<span class='redWord'>Special</span>") 
           .Replace("Perishable", "<span class='blueWord'>Perishable</span>") 
           .Replace("Danger", "<span class='yellowWord'>Danger</span>"); 
    } 
} 
0

在CellFormatting事件處理程序,添加以下代碼

void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
    { 
     if (e.Value != null && e.Value.ToString() == "Special") 
     { 
      e.CellStyle.ForeColor = Color.Red; 
     } 
    } 
+0

感謝Juniaith,但是這個代碼改變顏色首先在你的aspx代碼中創建CSS類我想要改變這個詞的顏色! – BaHaR

+0

如果你想改變一個特定單詞的顏色,你必須使用類似於RichEditTextColumn給定[這裏](http://www.codeproject.com/Articles/31823/RichTextBox-Cell-in-a-DataGridView)的自定義列, – Junaith

相關問題