How to highlight search results in gridview using asp.net?

I am using a search box to sort my gridview according to the search text. I want to highlight the matching text in the gridview entered into the textbox. This is my aspx page-

<table>
    <tr>
      <td>
         <asp:TextBox ID="TextBox1" runat="server" Width="167px">
         </asp:TextBox>
      </td>
    </tr>
    <tr>
       <td>
           <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
                Text="Submit" Width="116px" />
       </td>
    </tr>
    <tr>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </tr>
</table>
code behind
public void bind()
{
     dt = g1.return_dt("select  * from tbl1 where id is  not null  " 
           + Session["Name"] + "  order by  compname ");
     if (dt.Rows.Count > 0)
     {
         adsource = new PagedDataSource();
         adsource.DataSource = dt.DefaultView;
         adsource.PageSize = 10;
         adsource.AllowPaging = true;
         adsource.CurrentPageIndex = pos;
         btnfirst.Enabled = !adsource.IsFirstPage;
         btnprevious.Enabled = !adsource.IsFirstPage;
         btnlast.Enabled = !adsource.IsLastPage;
         btnnext.Enabled = !adsource.IsLastPage;
         GridView1.DataSource = adsource;
         GridView1.DataBind();
     }
     else
     {
        GridView1.DataSource = null;
        GridView1.DataBind();
     }
}

protected void Button1_Click(object sender, EventArgs e)
{
    if (TextBox1.Text != "")
    {
        Session["Name"] = string.Format("and  compname  like '%{0}%' or productcategory like '%{0}%' or country like '%{0}%'");
    }
    else
    {
         Session["Name"] = null;
    }
}

Please guide me how can I do this.

Answers


You can do it in two ways:

  1. Modify the text in the relevant columns of you data table. (Find the text in each column and add an span with css class surrounding that text.) Here is a sample:

    foreach(DataRow dr in dt.Rows) { foreach(DataColumn dc in dt.Columns) { string s = Convert.ToString(dr[dc.ColumnName]); s = s.Replace("Your Search Text","<span style='color:RED'>Your Search Text</span>"); dr[dc.ColumnName] = s; } }

  2. You can use javascript for the same and let the browser do all the hardwork. (Refer this link for a sample.)

Hope this helps.


Need Your Help

Error from simply initializing a variable?

python recursion boggle

While putting together a Boggle solver, I ran into some strange behavior I was hoping someone could explain to me. I got the function to return a set of possible words, and all I seemed to be missi...

How to redirect iframe users?

javascript html iframe web

I have a website: galiro.com/summer.html