roa765
roa765

Reputation: 295

Highlight keywords that exist in a table in SQL in a specific column in a gridview if they exist

I have a SQL table that contains some keywords. I have a row data bound method in my ASP.net code that loops through each keyword and currently it highlights the entire cell in the gridview if the word exists. I am trying to only highlight the keyword and not the entire cell.

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

E.g. if one of my keywords is 'Dog' I expect the output to be The dog is chasing the cat. The word dog is highlighted not the whole sentance

Upvotes: 2

Views: 305

Answers (1)

roa765
roa765

Reputation: 295

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

Upvotes: 1

Related Questions