Monday 28 May 2012

Search and highlight Results in Grdiview


Step1:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="searchhigh.aspx.cs" Inherits="searchhigh" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search and highlight Results in Grdiview
</title>
<style type="text/css">
.highlight {text-decoration:none; font-weight:bold;
color:black; background:yellow;}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1"
                  runat="server" />
<asp:UpdatePanel ID="UpdatePanel1"
                runat="server">
<ContentTemplate>
<div>
<asp:GridView ID="grdSearch" runat="server"
    BackColor="white" BorderColor="Aqua"
    AutoGenerateColumns="false" ShowFooter="true"
    OnRowCommand="grdSearch_RowCommand">
    <FooterStyle BackColor="AliceBlue"
    ForeColor="AntiqueWhite" />
    <PagerStyle BackColor="#99CCCC"
    ForeColor="#003399" HorizontalAlign="Left" />
    <HeaderStyle BackColor="#003399"
    Font-Bold="True" ForeColor="#CCCCFF" />

<Columns>
    <asp:TemplateField HeaderText="FirstName">
    <ItemTemplate>
    <asp:Label ID="lblname" runat="server"
Text='<%# Highlight(Eval("name").ToString()) %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtSearch" runat="server"
         Width="70px"></asp:TextBox>
    <asp:Button ID="btnSearch"
                CommandName="Search"
                runat="server" Text="Search"
                Width="60px" />
    </FooterTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="organization"
         HeaderText="Org" />
</Columns>
     </asp:GridView>
     </div>
     </ContentTemplate>
     </asp:UpdatePanel>
     <asp:UpdateProgress ID="UpdateProgress1"
                         runat="server">
     <ProgressTemplate>
     <br />
     <img src="Images/ajax.gif"
          alt="Searchig"  />
     </ProgressTemplate>
     </asp:UpdateProgress>
</form>
</body>
</html>


Step 2 :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Data.SqlClient;

public partial class searchhigh : System.Web.UI.Page
{
    public SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Con"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private DataTable GetRecords()
    {

        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select top 5 * from msppt_com_impact.ASAXPartnerEDM_Reg order by id asc";
        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(string strSearchText)
    {
        DataTable dt = GetRecords();
        DataView dv = new DataView(dt);
        string SearchExpression = null;
        if (!String.IsNullOrEmpty(strSearchText))
        {
            SearchExpression = string.Format("{0} '%{1}%'",
            grdSearch.SortExpression, strSearchText);

        }
        dv.RowFilter = "name like" + SearchExpression;
        grdSearch.DataSource = dv;
        grdSearch.DataBind();
    }
    protected void grdSearch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        System.Threading.Thread.Sleep(2000);
        if (e.CommandName == "Search")
        {
            TextBox txtGrid = (TextBox)grdSearch.FooterRow.FindControl("txtSearch");
            SearchText(txtGrid.Text);
        }
    }
    public string Highlight(string InputTxt)
    {
        GridViewRow gvr = grdSearch.FooterRow;
        if (gvr != null)
        {
            TextBox txtExample = (TextBox)grdSearch.FooterRow.FindControl("txtSearch");

            if (txtExample.Text != null)
            {
                string strSearch = txtExample.Text;
                // Setup the regular expression

                Regex RegExp = new Regex(strSearch.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;

            }
            else
                return InputTxt;
        }
        else
        {
            return InputTxt;
        }
    }

    public string ReplaceKeyWords(Match m)
    {
        return "<span class=highlight>" + m.Value + "</span>";
    }
}

Step 1: 


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="serchhilight.aspx.cs" Inherits="serchhilight" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Grid Search example</title>
    <style type="text/css">
    .highlight {
    text-decoration:none; font-weight:bold;
    color:black; background:yellow;}
    </style>
</head>
<body>
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />

    <div>
            Enter name to search:
    </div>
    <div>
        <asp:TextBox ID="txtSearch" runat="server"
AutoPostBack="True"
OnTextChanged="txtSearch_TextChanged">
</asp:TextBox>&nbsp;
    </div>
    <div>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                 <asp:GridView ID="grdSearch" runat="server" AutoGenerateColumns="false">
                        <Columns>
                            <asp:TemplateField HeaderText="Name">
                                <ItemTemplate>
                                    <asp:Label ID="lblname"
runat="server"
Text='<%# Highlight(Eval("name").ToString()) %>'>
</asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Org">
                                <ItemTemplate>
                                    <asp:Label ID="lblorg" runat="server" Text='<%#(Eval("organization")) %>'></asp:Label>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                            <asp:TemplateField HeaderText="Des">
                                <ItemTemplate>
                                    <asp:Label ID="lbldes" runat="server" Text='<%#(Eval("designation")) %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                </asp:GridView>
            </ContentTemplate>
        <Triggers>
        <asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
        </Triggers>
        </asp:UpdatePanel>

    </div>

</form>
</body>
</html>




Step 2:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

public partial class serchhilight : System.Web.UI.Page
{
    public SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Con"].ToString());

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private DataTable GetRecords()
    {
       
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select top 5 * from msppt_com_impact.ASAXPartnerEDM_Reg order by id asc";
        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 = "name 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 "<span class=highlight>" + m.Value + "</span>";

    }

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

No comments:

Post a Comment