<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Highlighting" %>
<!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 runat="server">
<title>Sample Search Highlighting</title>
<style type="text/css">
.myPanel { margin: 8pt; width: 50%; padding 10pt; }
body { font-family: Tahoma, Arial; font-size: 10pt;}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="panSearch" runat="server" GroupingText="Search" CssClass="myPanel">
Enter Search expression:
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox><br />
<asp:Button ID="btnSearch" runat="server" OnClick="btnSearch_Click" Text="Search" />
</asp:Panel>
<asp:Panel ID="panContent" runat="server" GroupingText="Content" CssClass="myPanel">
<asp:Label ID="labContent" runat="server" />
</asp:Panel>
</form>
</body>
</html>
File: Default.aspx.cs
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.Text.RegularExpressions;
public partial class Highlighting : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
labContent.Text = "Client-side validation is useful because it reduces round-trips to the server. This provides immediate feedback to the user as well as improves server performance. Unfortunately, client-side validation by itself is not sufficient. The user could be using a browser that does not support scripting (that is, using an ancient browser or has scripting turned off via the browser preferences). As well, client-side scripting is potentially vulnerable to script exploits. These can happen when a malicious user enters a javascript <script> block into a text field that can later cause harm when the entered data is echoed back to the browser.";
}
protected void btnSearch_Click(object sender, EventArgs e)
{
Regex myreg = new Regex(txtSearch.Text, RegexOptions.IgnoreCase);
labContent.Text = myreg.Replace(labContent.Text, new MatchEvaluator(ReplaceSearchWord));
}
public string ReplaceSearchWord(Match m)
{
return "<span style='font-weight:bold; background: yellow;'>" + m.Value + "</span>";
}
}