Tuesday, July 7, 2009

Gridview Highlight Search

ASPX Page
---------


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

<!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>Untitled Page</title>
<style type="text/css">

.highlight
{
background:Yellow;
}

</style>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter Search Keyword:
<asp:TextBox ID="txtSearchBox" runat="server" Text="Ca" />
<asp:Button ID="Btn_Search" OnClick="Search" runat="server" Text="Search" />
<br />
<br />
<br />
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false" AllowPaging="True"
Font-Size="Large" OnPageIndexChanging="gvProducts_PageIndexChanging" PageSize="10">
<Columns>
<asp:TemplateField HeaderText="Product Name">
<ItemTemplate>
<asp:Label ID="lblProductName" runat="server" Text='<%# SearchKeyWord( searchWord,(string) Eval("emp_name") ) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
 
<asp:Panel ID="Panel1" runat="server" Height="50px" Width="263px">
</asp:Panel>
<br />
<br />
<br />
 </div>
</form>
</body>
</html>


Code Behind Page
----------------

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 _Default : System.Web.UI.Page
{
protected string searchWord = String.Empty;
private const int PAGE_SIZE = 10;

private Hashtable hMatches = new Hashtable();

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}

CreateLinks();


}

private void CreateLinks()
{
Hashtable myHashTable = ViewState["MyHashTable"] as Hashtable;

if(myHashTable != null && myHashTable.Count > 0)
{

foreach (object key in new ArrayList(myHashTable.Keys))
{
LinkButton link = new LinkButton();
link.Command += new CommandEventHandler(link_Command);
link.CommandArgument = key.ToString();
link.Text = String.Format("There are {0} results on page {1}",myHashTable[key].ToString() , (Convert.ToInt32(key) + 1).ToString()) + "
";

Panel1.Controls.Add(link);
}

Panel1.DataBind();
}
}


private void BindData()
{
string connectionString = "Server=SERVERNAME;Database=TestDB;user=rsmsuser;pwd=rsmsuser";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT emp_id, emp_name FROM ali_employee", myConnection);

DataSet ds = new DataSet();
ad.Fill(ds);

gvProducts.DataSource = ds;
gvProducts.DataBind();
}

protected void Search(object sender, EventArgs e)
{
// clear the old results
Panel1.Controls.Clear();
Panel1.DataBind();

searchWord = txtSearchBox.Text;
SearchContainer(searchWord);

// Hmmm
BindData();

}

protected string SearchKeyWord(string searchString, string text)
{
Regex reg = new Regex(searchString.Replace(" ", "|"), RegexOptions.IgnoreCase);
return reg.Replace(text,new MatchEvaluator(ReplaceKeyWords));

}

private void SearchContainer(string searchString)
{
int index = 0;

// get the container
DataSet ds = GetDataSet();


double pageIndex = 0;

Regex reg = new Regex(searchString.Replace(" ","|"),RegexOptions.IgnoreCase);

foreach(DataRow row in ds.Tables[0].Rows)
{
if (reg.IsMatch(row["emp_name"] as String))
{
pageIndex = Math.Ceiling( Convert.ToDouble( index / PAGE_SIZE ));

if (hMatches.ContainsKey(pageIndex))
{
hMatches[pageIndex] = ((int)hMatches[pageIndex]) + 1;
}
else
{
hMatches.Add(pageIndex, 1);
}
}

index++;
}

ViewState["MyHashTable"] = hMatches;

CreateLinks();


}

void link_Command(object sender, CommandEventArgs e)
{
gvProducts.PageIndex = Convert.ToInt32( e.CommandArgument);
searchWord = txtSearchBox.Text;
BindData();
}

private DataSet GetDataSet()
{
string connectionString = "Server=SERVERNAME;Database=TestDB;user=rsmsuser;pwd=rsmsuser";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT emp_id, emp_name FROM ali_employee", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

return ds;
}

private string ReplaceKeyWords(Match m)
{
return "" + m.Value + "";
}

protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex;
searchWord = txtSearchBox.Text;
BindData();
}
}

No comments: