明日茶座 |
 |
|
|
|
|
|
视频中心 |
 |
|
|
|
|
|
经验技巧 |
 |
|
|
|
|
|
|
|
|
技巧名称: |
实现多个搜索关键字在GridVewi中描红显示 |
添加时间: |
2010-07-05 |
作者: |
房大伟 |
技巧类别: |
ASP.NET |
实现搜索GridView多个关键字高亮显示
运行效果
应用ASP.NET实现搜索GridView关键字高亮显示,并支持多个关键字的搜索功能,以方便用户查找的关键字更加醒目突出。
关键技术
主要使用Replace方法,该方法可以替换掉一个字符串中的某些特定字符或者子串。语法格式如下。
public string Replace (string oldValue,string newValue)
参数说明如下。
 oldValue:要替换的字符。
 newValue:要替换oldValue的所有匹配项的字符。
说明:在搜索关键词高亮中一般的方法都是采用替换的办法(Replace)这个方法有一个缺点就是不能区分大小写的问题。可以使用用正则表达式的方法来解决这个问题,并且效率也比较高。
设计过程
(1)新建一个网站将其命名为EvalReplace,默认主页为Default.aspx,在该主页中添加一个GridView控件绑定商品信息。
(2)在后台代码中,主要编写了一个自定义Highlightkeywords()方法实现支持多个关键字搜索高亮显示的功能,具体代码如下:
/// <summary>
/// 替换关键字为红色
/// </summary>
/// <param name="keycontent">原始内容</param>
/// <param name="k">关键字,支持多关键字</param>
/// <returns>String</returns>
/// <author>haver Guo</author>
public string Highlightkeywords(string keycontent, string k)
{
string resultstr = keycontent;
if (k == "") //如果不存在搜索的关键字,返回原状态
{
return keycontent;
}
if (k.Trim().IndexOf(',') > 0)
{
string[] myArray = k.Split(','); //多个关键字搜索,以(,)来分隔
for (int i = 0; i < myArray.Length; i++)//存在搜索的关键字以描红方式显示
{
resultstr = resultstr.Replace(myArray[i].ToString(), "<span class='highlightTxtSearch'>" + myArray[i].ToString() + "</span>");
}
return resultstr;
}
else
{
return resultstr.Replace(k, "<span class='highlightTxtSearch'>" + k + "</span>");
}
}
心法领悟001: 使用正则表达式解决(Replace)方法不能区分大小写的问题
使用正则表达式解决(Replace)方法不能区分大小写的问题,代码如下:
public static string HighLightKeyWord(string pain,string keyword)
{
//搜索关键词高亮函数By JN 2006.11.30
System.Text.RegularExpressions.MatchCollection m = Regex.Matches(pain, keyword, RegexOptions.IgnoreCase);
//忽略大小写搜索字符串中的关键字
for (int j = 0; j < m.Count; j++)//循环在匹配的子串前后
{
//j×31为插入html标签使pain字符串增加的长度:
pain = pain.Insert((m[j].Index + keyword.Length + j * 31), "</font>");//关键字后插入html标签
pain = pain.Insert((m[j].Index + j * 31), "<font color=#ff0000>");//关键字前插入html标签
}
return pain;
}
|
|
|