search and highlight rows in gridview using C#

Nomfundo Cindi
Nomfundo Cindi used Ask the Experts™
on
I have a gridview that is populated on page load. I added a search option and when user clicks button I want the matching row to be highlighted in gridview. The grid will display all the data but will only highlight the matching row. Below is my code but it doesn't highlight the matching row. Any suggestions?

Highlight search code:
Hide   Copy Code
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Text = Regex.Replace(e.Row.Cells[0].Text, RefNo.Text.Trim(), delegate (Match match)
            {
                return string.Format("<span style = 'background-color:#D9EDF7'>{0}</span>", match.Value);
            }, RegexOptions.IgnoreCase);
        }
    }
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
Highlight search code:

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Text = Regex.Replace(e.Row.Cells[0].Text, RefNo.Text.Trim(), delegate (Match match)
            {
                return string.Format("<span style = 'background-color:#D9EDF7'>{0}</span>", match.Value);
            }, RegexOptions.IgnoreCase);
        }
    }
Your code does highlight search portion of first cell text. To highlight row (or cell) use
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var source = e.Row.Cells[0].Text;
        var search = RefNo.Text.Trim();
        if (source != "" && search != "" && source.Contains(search))
        {
            e.Row.BackColor = System.Drawing.Color.Yellow;
            //to highlight cell
            //e.Row.Cells[0].BackColor = System.Drawing.Color.Yellow;
        }
    }
}

Open in new window

Note: you need call GridView.DataBind(); each time Page_Load to fire OnRowDataBound event. If you don't need perform any server action on selection I suggest using client side code (javascript) to select matching row.
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: Ark (https:#a42048809)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

frankhelk
Experts-Exchange Cleanup Volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial