Search Records In GridView And Highlight Results Asp.Net Ajax

In this example i am Explaining how to Search Records In GridView And Highlight Results Using Ajax In Asp.Net 2.0,3.5,4.0 based on text entered in textbox.



Add following CSS style in head section of page.

HTML SOURCE
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
    
Enter first name to search:
 
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True"
             OnTextChanged="txtSearch_TextChanged"/>
 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch" runat="server"
              AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" 
           Text='<%# Highlight(Eval("FirstName").ToString()) %>'/>
</ItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#(Eval("LastName")) %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#(Eval("Location")) %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

Write following code in code behind
C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private DataTable GetRecords()
    {
        SqlConnection conn = new SqlConnection(strConnection);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select * from Employees";
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        DataSet objDs = new DataSet();
        dAdapter.Fill(objDs);
        return objDs.Tables[0];

    }
    private void BindGrid()
    {
        DataTable dt = GetRecords();
        if (dt.Rows.Count > 0)
        {
            grdSearch.DataSource = dt;
            grdSearch.DataBind();
        }
    }
    private void SearchText()
    {
        DataTable dt = GetRecords();
        DataView dv = new DataView(dt);
        string SearchExpression = null;
        if (!String.IsNullOrEmpty(txtSearch.Text))
        {
            SearchExpression = string.Format("{0} '%{1}%'",
            grdSearch.SortExpression, txtSearch.Text);

        }
        dv.RowFilter = "FirstName like" + SearchExpression;
        grdSearch.DataSource = dv;
        grdSearch.DataBind();

    }
    public string Highlight(string InputTxt)
    {
        string Search_Str = txtSearch.Text.ToString();
        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(),
        RegexOptions.IgnoreCase);

        // Highlight keywords by calling the 
        //delegate each time a keyword is found.
        return RegExp.Replace(InputTxt,
        new MatchEvaluator(ReplaceKeyWords));

        // Set the RegExp to null.
        RegExp = null;

    }

    public string ReplaceKeyWords(Match m)
    {

        return "" + m.Value + "";

    }

    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        SearchText();
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  BindGrid()
 End If
End Sub
Private Function GetRecords() As DataTable
 Dim conn As New SqlConnection(strConnection)
 conn.Open()
 Dim cmd As New SqlCommand()
 cmd.Connection = conn
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "Select * from Employees"
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 Dim objDs As New DataSet()
 dAdapter.Fill(objDs)
 Return objDs.Tables(0)

End Function
Private Sub BindGrid()
 Dim dt As DataTable = GetRecords()
 If dt.Rows.Count > 0 Then
  grdSearch.DataSource = dt
  grdSearch.DataBind()
 End If
End Sub
Private Sub SearchText()
 Dim dt As DataTable = GetRecords()
 Dim dv As New DataView(dt)
 Dim SearchExpression As String = Nothing
 If Not [String].IsNullOrEmpty(txtSearch.Text) Then

  SearchExpression = String.Format("{0} '%{1}%'", grdSearch.SortExpression, txtSearch.Text)
 End If
 dv.RowFilter = "FirstName like" & SearchExpression
 grdSearch.DataSource = dv
 grdSearch.DataBind()

End Sub
Public Function Highlight(InputTxt As String) As String
 Dim Search_Str As String = txtSearch.Text.ToString()
 ' Setup the regular expression and add the Or operator.
 Dim RegExp As New Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase)

 ' Highlight keywords by calling the 
 'delegate each time a keyword is found.
 Return RegExp.Replace(InputTxt, New MatchEvaluator(AddressOf ReplaceKeyWords))

 ' Set the RegExp to null.
 RegExp = Nothing

End Function

Public Function ReplaceKeyWords(m As Match) As String

 Return "" & Convert.ToString(m.Value) & ""

End Function

Protected Sub txtSearch_TextChanged(sender As Object, e As EventArgs)
 SearchText()
End Sub

If you like this post than join us or share

18 comments:

Anonymous said...

Nice article


Anonymous said...

Thanks your article!


گزارش said...

thanks for the article.it saved me a lot of research for doing such things


Anonymous said...

Very Nice Article. Lot useful in many Scenarios


Mora said...

Great Article !!


Shakti Singh Dulawat said...

This is very nice example mention my you, this is helpful for programming logic.
Thanks
Shakti
www.nextmvp.blogspot.com


Anonymous said...

Very nice example thanx


Anonymous said...

how to do if the gridview is multi-page?


Danish Wadhwa said...

Hey..! Quite convinced with you post.

Actually i am new to ASP and if the same thing i want to do with Access Database...What are the few changes which i have to consider..!


Danish said...

Hello Nice Post..!
Can you help me to resolve this error and i am using an Access Database in my application..!
Will be waiting for you reply.

ERROR: Type or namespace definition, or end-of-file expected

Danish Wadhwa
You can reply me on my Email
me@danishwadhwa.com


Anonymous said...

it is very usefull article, but from my point of view this will be more userfriendly if there will no need to press enter button.
Thanking you


Anonymous said...

Good Article.
But I am having an error accessing the m value. I am doing in VB and thus it says - m not accessible bcoz of protection level. I tried to use
return RegExp.Replace(InputTxt,
new MatchEvaluator(addressof((ReplaceKeyWords(m))))
Which is throwing error at m.
Would be great if posted in vb.


Anonymous said...

Hey,great article..helped me a lot.
thanks dude.


Pé Zin said...

Great!


Anonymous said...

It's very easy to understand and very useful thanks for ur submit this article.
this type of searching m finding few days.

Thanks
Twinkle Kumar


Robbie Mills said...

Great article, there is a slightly different example which I think is a bit simpler at http://blog.evonet.com.au/post/2008/06/25/Gridview-with-highlighted-search-results.aspx


Unknown said...

im getting error Error 11 '_Default.GetRecords()': not all code paths return a value


hazim saleh said...

nice


Find More Articles