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 ...
https://www.programming-free.com/2012/12/aspnet-ajax-search-highlight-results-in.html?m=0
ASP.NET Gridview is a very powerful control that can display content with options such as sorting and paging. One more feature that a gridview often requires when it contains large volume of data, is 'Searching'. For example, when a manager goes through a gridview that displays employee information and interested only on the information about the employee he is supervising, it will be very easy for him to find that particular record if he had a search box enabled on the employee name column of the gridview. In this post, I am going to explain how to implement asynchronous searching and highlighting the search terms in a gridview based on any one column in the gridview. By asynchronous searching I mean, updating the grid view with the search results without reloading the whole page. After you understand the basic concept of how to implement this, you can also extend the requirement by making the gridview searchable on multiple columns of it.
1. For this example I have used a mysql table named as "employee" with the following structure,
+-------------+-------------+| Field | Type |+-------------+-------------+| id | int(11) | | name | varchar(20) || designation | varchar(20) || salary | varchar(20) |+-------------+-------------+
Create a table with the above structure. This is required because we are going to enable search on the 'name' column of this table.
2. Clear the Html content in your .aspx page. Copy and paste the below code instead,
<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>
In the above html code, I have added style element to add some css for highlighting the search terms in the search result.
A ScriptManager control and UpdatePanel control is added for implementing AJAX functionality to the search implementation. Note that grid view is placed inside the UpdatePanel control to ensure that everytime when the user clicks in search button, only the gridview gets reloaded and not the whole page. If you are new to AJAX and for a basic understanding of how AJAX works in ASP.NET, please see this.
In the Grid View,
- 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.
Finally, an UpdateProgress control to display the progress of search operation.
3. In the code-behind page, add the following namespaces.
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