AJAX Search & Highlight Results in GridView
ASP.NET Gridview is a very powerful control that can display content with options such as sorting and paging. One more feature that ...

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>AJAX Search & Highlight in GridView</title> <style type="text/css"> .highlight { text-decoration:none; font-weight:bold; color:black; background:yellow; } </style> </head> <body> <form id="form1" runat="server"> <div> <h1>AJAX Search & Highlight in GridView</h1> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <div> <asp:Label ID="lblAlert" runat="server" Visible="false" Text="There are no results matching your search input. Please try again with different input"></asp:Label> <asp:GridView ID="grdToSearch" runat="server" BackColor="white" BorderColor="Aqua" AutoGenerateColumns="false" ShowFooter="true" OnRowCommand="grdToSearch_RowCommand"> <FooterStyle BackColor="DarkOrange" ForeColor="AntiqueWhite" /> <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" /> <HeaderStyle BackColor="DarkOrange" Font-Bold="True" ForeColor="White" /> <Columns> <asp:BoundField DataField="id" HeaderText="ID" /> <asp:TemplateField HeaderText="Name"> <ItemTemplate> <asp:Label ID="lblFIrstName" 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" /> <asp:Button ID="btnBack" CommandName="Back" runat="server" Text="Back" Visible="false" Width="60px" /> </FooterTemplate> </asp:TemplateField> <asp:BoundField DataField="designation" HeaderText="Designation" /> <asp:BoundField DataField="salary" HeaderText="Salary" /> </Columns> </asp:GridView> </div> </ContentTemplate> </asp:UpdatePanel> <asp:UpdateProgress ID="UpdateProgress1" runat="server"> <ProgressTemplate> <br /> <img src="Images/ajax-loading.gif" alt="Searching.. Please wait!"/> </ProgressTemplate> </asp:UpdateProgress> </div> </form> </body> </html>
- There is an alert label that is used to display warning message whenever the grid view date does not have any match for the search terms.
- A footer template that has the search box typically a text box, a search button, that triggers the row_command event of the gridview whenever it is clicked and a back button which helps users to get back to the original result ( hidden initially on page load and displayed only when search results are displayed).
- An Item template that displays value for Name column as labels. Whenever a value is displayed in the name column it checks for value in the search text box to highlight search terms if present.
using System.Data; using System.Text.RegularExpressions;
4. Copy and paste the below code inside the code-behind file,
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Load gridview with data on page load
BindGrid();
}
}
private DataTable GetRecords()
{
try
{
//Fetch data from mysql database
MySqlConnection conn = new MySqlConnection("server=localhost;uid=root;password=priya123;database=test; pooling=false;");
conn.Open();
string cmd = "select * from employee";
MySqlDataAdapter dAdapter = new MySqlDataAdapter(cmd,conn);
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];
}
catch (MySqlException ex)
{
System.Console.Error.Write(ex.Message);
return null;
}
}
private void BindGrid()
{
//Fetch data from mysql database
DataTable dt = GetRecords();
//Bind the fetched data to gridview
grdToSearch.DataSource = dt;
grdToSearch.DataBind();
}
private void SearchText(string strSearchText)
{
lblAlert.Visible = false;
DataTable dt = GetRecords();
DataView dv = new DataView(dt);
string SearchExpression = null;
if (!String.IsNullOrEmpty(strSearchText))
{
SearchExpression = string.Format("{0} '%{1}%'",
grdToSearch.SortExpression, strSearchText);
}
dv.RowFilter = "name like" + SearchExpression;
if (dv.Count > 0)
{
grdToSearch.DataSource = dv;
grdToSearch.DataBind();
// Enable button that allow users to get back to the main gridview
Button backbutton = (Button)grdToSearch.FooterRow.FindControl("btnBack");
backbutton.Visible = true;
}
else
{
//Display alert message when there are no matching search results
lblAlert.Visible = true;
}
}
protected void grdToSearch_RowCommand(object sender, GridViewCommandEventArgs e)
{
System.Threading.Thread.Sleep(2000);
if (e.CommandName == "Search")
{
TextBox txtGrid = (TextBox)grdToSearch.FooterRow.FindControl("txtSearch");
SearchText(txtGrid.Text);
}
else if (e.CommandName == "Back")
{
BindGrid();
}
}
public string Highlight(string InputTxt)
{
GridViewRow gvr = grdToSearch.FooterRow;
if (gvr != null)
{
TextBox txtExample = (TextBox)grdToSearch.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));
}
else
return InputTxt;
}
else
{
return InputTxt;
}
}
public string ReplaceKeyWords(Match m)
{
return "" + m.Value + "";
}
}
Order of execution and explanation of the above code:
- Initially, we are loading the grid view with data in the Page_Load event.
- Whenever an user clicks on the search button in the grid view, rowcommand event of the gridview is triggered.
- RowCommand event checks for the CommandName, which is "Search" in case if the user clicks the search button and then SearchText() method is called.
- SearchText() method is responsible for the actual searching - It uses RowFilter to filter results based on the column "name".
- Highlight() method is responsible for text highlighting. It matches the value in the search text box which each record in the gridview using regular expression functionality and highlights the results in yellow color making use of the css class used in the .aspx page.
5. That is all you have to do to implement search in grid view and highlighting of search terms in the results. Run the application and look for similar output as shown below.
Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts.Thanks for reading!!
Compiler Error Message: BC30456: 'grdToSearch_RowCommand' is not a member of 'ASP.default_aspx'.
ReplyDeleteHi,
DeleteAre you sure you added grdToSearch_RowCommand event to your code-behind file? Also please make sure whether the event name in the code behind file and the declaration OnRowCommand="eventname" matches.
Hope this helps!
Hello there! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Nonetheless, Cheap Essay Writer I’m definitely delighted I found it and I’ll be book-marking and checking back often!
ReplyDeleteHi visitors! Thanks so much for this useful info, that you posted here in this blog, I really appreciate it! But what about studying, this is my second time using this website and it never fails me (you can read paymetodoyourhomework review here). Did a great well organized and written assignment and helped me put everything I was thinking to paper professionally. Will definitely be in favorites and first choice!!!
ReplyDelete