【问题标题】:change forecolor af a special word in gridview cell在gridview单元格中更改特殊单词的前景色
【发布时间】:2014-02-10 20:06:16
【问题描述】:

我想改变一些特殊词而不是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。我该怎么办?

【问题讨论】:

    标签: c# css asp.net gridview colors


    【解决方案1】:

    结合使用 span tags 和 CSS 类。首先在您的 aspx 代码中创建 CSS 类:

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

    然后将所有出现的Special 替换为&lt;span class='redWord'&gt;Special&lt;/span&gt;,将Perishable 替换为&lt;span class='blueWord'&gt;Perishable&lt;/span&gt;,并将Danger 替换为&lt;span class='yellowWord'&gt;Danger&lt;/span&gt;

    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>");
        }
    }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 感谢 Juniaith,但是这段代码改变了整个单元格的颜色,我只想改变那个词的颜色!!
      • 如果您想更改特定单词的颜色,您必须使用类似于 RichEditTextColumn 的自定义列给定here
      猜你喜欢
      • 2013-08-20
      • 2013-06-28
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2021-03-10
      • 1970-01-01
      相关资源
      最近更新 更多