在gridview单元格中更改forecolor af特殊单词

时间:2014-01-21 09:51:59

标签: c# css asp.net gridview colors

我想更改某些特殊字的颜色,而不是更改gridview单元格中的所有字词。  这是代码:

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 个答案:

答案 0 :(得分:2)

使用span tags和CSS类的组合。首先在aspx代码中创建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>");
    }
}

答案 1 :(得分:0)

在CellFormatting事件处理程序中,添加以下代码

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