首页 > 解决方案 > 如果存在,则在网格视图的特定列中突出显示 SQL 表中存在的关键字

问题描述

我有一个包含一些关键字的 SQL 表。我的 ASP.net 代码中有一个行数据绑定方法,该方法循环遍历每个关键字,如果该单词存在,它当前会突出显示 gridview 中的整个单元格。我试图只突出关键字而不是整个单元格。

protected void gvRejectedQueue_RowDataBound(object sender, GridViewRowEventArgs e)
{
    string connectionstring = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    SqlConnection cn = new SqlConnection(connectionstring);
    SqlCommand cmd = new SqlCommand("SELECT KEYWORD FROM cr_tbl_BI_CRAMRR_KeyWords", cn);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable ds = new DataTable();
    da.Fill(ds);

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        foreach (DataRow row in ds.Rows)
        {
            string sr = null;
            sr = e.Row.Cells[3].Text;
            if (sr.Contains(row["Keyword"].ToString()) == true)
            {
                e.Row.Cells[3].BackColor = System.Drawing.Color.Yellow;
            }
        }
    }
}

例如,如果我的关键字之一是“Dog”,我希望输出是 The dog is chasing the cat。突出显示狗这个词而不是整个句子

标签: c#sqlgridview

解决方案


if (sr.Contains(row["Keyword"].ToString()) == true)
{                
   e.Row.Cells[3].Text = e.Row.Cells[3].Text.Replace(row["Keyword"].ToString(), "<span style='background-color:yellow'>" + row["Keyword"].ToString() + "</span>");
}

推荐阅读