Thursday, November 1, 2012

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

No comments:

Post a Comment