MatchEvaluator Delegate of a Regular Expression Replace Method in ASP.Net

Introduction

This article explains the MatchEvaluator Delegate. You can use this delegate method to perform a custom verification for each match found by a Regular Expression Replace method. For each matched string, the Replace method calls the MatchEvaluator delegate method with a Match object that represents the match.

System.Text.RegularExpressions Namespace

  1. using System.Text.RegularExpressions;

The System.Text.RegularExpressions namespace contains classes that provide access to the .NET Framework Regular Expression engine. This namespace has the the "Match" class that represents the results from a single Regular Expression match.

MatchEvaluator Delegate

The MatchEvaluator delegate represents the method that is called each time a Regular Expression match is found during a "Replace" method.

  1. return regex.Replace(InputTxt, new MatchEvaluator(MatchRecords));

In a specified input string, replaces all strings that match a specified Regular Expression with a string returned by a MatchEvaluator delegate. The Regex.Replace method processes text replacements. In a Replace method we pass two arguments, the first argument is the input and the second argument is the replacement string.

  1. public string MatchRecords(Match m)  
  2. {  
  3.     return ("<span class=highlight>" + m.Value + "</span>");  
  4. }   

The "Match" object represents the results from a single Regular Expression match.

FilterExpression Property

The FilterExpression property value is a format string expression or a string processed by the String.Format method and a filtering expression applied when data is retrieved using the Select method.

  1. <asp:SqlDataSource ID="dsDetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"  
  2.  SelectCommand="select * from EmployeeInformation" FilterExpression="Emp_Name LIKE '%{0}%'"> 

Now  I will show you how to search the records in a GridView using MatchEvaluator. Let's use the following procedure.

Create DataBase and Table in SQL Server

Create Database Employee

 

  1. use Employee  
  2. create table EmployeeInformation  
  3. (  
  4. EmpId int,  
  5. Emp_Name varchar(max),  
  6. Emp_Address nvarchar(max),  
  7. Emp_Department varchar(max)  
  8. )  

 

Write the following procedure to insert the values in the table's columns:

 

  1. insert into EmployeeInformation values(101,'Pankaj Lohani','A-43 Vinod New Delhi','Web Development')  
  2. insert into EmployeeInformation values(102,'Nimit Joshi','B-44 Laxminagar New Delhi','Web Development')  
  3. insert into EmployeeInformation values(103,'Pravesh Khanduri','C-45 Pratap Vihar New Delhi','Teacher')  
  4. insert into EmployeeInformation values(104,'Amit Senwal','D-46 R.K puram New Delhi','Web Development')  
  5. insert into EmployeeInformation values(105,'Ravi Kumar','E-47 Saket New Delhi','Testing')  
  6. insert into EmployeeInformation values(106,'Ainul Hasan','F-48 Saraswati Kunj New Delhi','Web Development')  
  7. insert into EmployeeInformation values(107,'Ashish','F-49 Vinod Nagar New Delhi','Software Engineer')   

Write the following query to execute the table schema:

  1. select * from EmployeeInformation  

TalbeSchema

Step 1

Open Visual Studio then select "Create New Website" --> ASP.NET Web Site.

CreateNewWebsite

Step 2

Now go to the Solution Explorer to the right side of the application and use the procedure shown in the following figure:

AddNewItem

Step 3

Add a new Web form in the empty web application as in the figure given below.

AddNewWebForm

Step 4

Write the following code in the GridForm.aspx page:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmployeeDetails.aspx.cs" Inherits="EmployeeDetails" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head id="Head1" runat="server">  
  5. <title>Highlight the Search Keywords in Gridview </title>  
  6. <style type="text/css">  
  7. .GridviewDiv {font-size: 100%; font-family: 'Lucida Grande''Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}  
  8. Table.Gridview{border:solid 1px #df5015;}  
  9. .Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}   
  10. .Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}  
  11. .Gridview tr{color: Black; background-color: White; text-align:left}  
  12. :link,:visited { color: #DF4F13; text-decoration:none }  
  13. .highlight {text-decoration: none;color:black;background:white;}  
  14. </style>  
  15. </head>  
  16. <body>  
  17. <form id="form1" runat="server">  
  18. <div class="GridviewDiv">  
  19. <p>  
  20. Enter Employee Name :  
  21. <asp:TextBox ID="txtsrchbox" runat="server" />  
  22. <asp:Button ID="btnSearch" Text="Search" runat="server"  
  23. Style="top:5px; position: relative" OnClick="btnSearch_Click1"/>    
  24. <asp:Button ID="btnClear" runat="server" Text="Clear" Style="top: 5px;position: relative" OnClick="btnClear_Click1"/><br />  
  25. <br />  
  26. </p>  
  27. <asp:GridView ID="gvEmpDetails" runat="server" AutoGenerateColumns="False" AllowPaging="True"  
  28. AllowSorting="True" DataSourceID="dsDetails" Width="540px" CssClass="Gridview" BackColor="White"   
  29. BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" >  
  30.     <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />  
  31. <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />  
  32.     <AlternatingRowStyle BackColor="#F7F7F7" />  
  33. <Columns>  
  34. <asp:TemplateField HeaderText="Emp_Id">  
  35. <ItemTemplate>  
  36. <asp:Label ID="lblEmpId" Text='<%# GetRecord(Eval("EmpId").ToString()) %>' runat="server"/>  
  37. </ItemTemplate>  
  38. </asp:TemplateField>  
  39.     <asp:TemplateField HeaderText="Emp_Name">  
  40. <ItemTemplate>  
  41. <asp:Label ID="lblEmpname" Text='<%# GetRecord(Eval("Emp_Name").ToString()) %>' runat="server"/>  
  42. </ItemTemplate>  
  43. </asp:TemplateField>  
  44. <asp:TemplateField HeaderText="Emp_Address">  
  45. <ItemTemplate>  
  46. <asp:Label ID="lblAddress" Text='<%# Eval("Emp_Address") %>' runat="server"/>  
  47. </ItemTemplate>  
  48. </asp:TemplateField>  
  49. <asp:TemplateField HeaderText="Emp_Department">  
  50. <ItemTemplate>  
  51. <asp:Label ID="lblDepartment" Text='<%#Eval("Emp_Department") %>' runat="server"></asp:Label>  
  52. </ItemTemplate>  
  53. </asp:TemplateField>  
  54. </Columns>  
  55.     <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />  
  56.     <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />  
  57.     <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />  
  58.     <SortedAscendingCellStyle BackColor="#F4F4FD" />  
  59.     <SortedAscendingHeaderStyle BackColor="#5A4C9D" />  
  60.     <SortedDescendingCellStyle BackColor="#D8D8F0" />  
  61.     <SortedDescendingHeaderStyle BackColor="#3E3277" />  
  62. </asp:GridView>  
  63. </div>  
  64. <asp:SqlDataSource ID="dsDetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"  
  65.  SelectCommand="select * from EmployeeInformation" FilterExpression="Emp_Name LIKE '%{0}%'">  
  66. <FilterParameters>  
  67. <asp:ControlParameter Name="Emp_Name" ControlID="txtsrchbox" PropertyName="Text" />  
  68. </FilterParameters>  
  69. </asp:SqlDataSource>  
  70. </form>  
  71. </body>  
  72. </html>   

Add the connectionstring string to the Web.Config file as in the following:

  1. <connectionStrings>  
  2. <add name="dbconnection" connectionString="Data Source=; Initial Catalog=Employee;   
  3. User=; Password=***" providerName="SqlClient"/>  
  4.  </connectionStrings>   

In the preceding EmployeeDetails.aspx page we have the TemplateField consisting of two templates, an ItemTemplate that has a Label whose Text property is set to the value of the Employeename data field, and the data-binding syntax:

  1. <asp:Label ID="lblEmpId" Text='<%# GetRecord(Eval("EmpId").ToString()) %>' runat="server"/>   

that indicates that the fieldName data field is bound to the specified Web control property.

Design View of EmployeeDetails.aspx

DesignViewofASPX

Now write the following code in EmployeeDetails.aspx.cs:

Step 5

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Text.RegularExpressions;  
  8. using System.Web.UI;  
  9. using System.Web.UI.WebControls;  
  10. public partial class EmployeeDetails : System.Web.UI.Page  
  11. {  
  12.     private string str = "";  
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.     }  
  16.     public string GetRecord(string InputTxt)  
  17.     {  
  18.         string srch = txtsrchbox.Text;  
  19.         Regex regex= new Regex(srch.Replace(" ""|").Trim(), RegexOptions.IgnoreCase);  
  20.         return regex.Replace(InputTxt, new MatchEvaluator(MatchRecords));  
  21.     }  
  22.     public string MatchRecords(Match m)  
  23.     {  
  24.         return ("<span class=highlight>" + m.Value + "</span>");  
  25.     }  
  26.     protected void btnSearch_Click1(object sender, EventArgs e)  
  27.     {  
  28.         str = txtsrchbox.Text;  
  29.     }  
  30.     protected void btnClear_Click1(object sender, EventArgs e)  
  31.     {  
  32.         txtsrchbox.Text = "";  
  33.         str = "";  
  34.         gvEmpDetails.DataBind();  
  35.     }  
  36. }   

Step 6

Debug the application by pressing F5 to execute the Web form. After debugging the application the output will be as in the following figure:

AfterDebug

Step 7

Now write the incomplete name on a given TextBox then click on the search button as in the figure given below.

SearchEmployee1

Step 8

Now search the employee details through the single char of the name and click on the search button as in the figure given below.

SeachwithSinglechar

Step 9

Search the details by the last name of the employee as in the figure given below.

SearchingwithLastName


Similar Articles