change forecolor af a special word in gridview cell

前端 未结 2 1774
有刺的猬
有刺的猬 2021-01-22 23:21

I want to change the color of some special words NOT all words in a gridview cell. Here is the code:

protected void gvContents_RowDataBound(obj         


        
相关标签:
2条回答
  • 2021-01-22 23:38

    In the CellFormatting event handler, add the below code

    void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.Value != null && e.Value.ToString() == "Special")
            {
                e.CellStyle.ForeColor = Color.Red;
            }
        }
    
    0 讨论(0)
  • 2021-01-22 23:43

    Use a combination of span tags and CSS classes. First create the CSS classes in your aspx code:

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

    then replace all occurences of Special to <span class='redWord'>Special</span>, Perishable to <span class='blueWord'>Perishable</span>, and Danger to <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 讨论(0)
提交回复
热议问题