搜索后用黄色高亮关键字的效果(不区分大小写)

你所说的是用DataGrid,但我用我的实例是Repeater说明。其实原理是一样的。 
在ItemTemplate中加一个服务器控件用于显示主题 
实例中是HyperLink,用Label也行,注意设置好的ID=SubjectHyperLink,后台代码会用到。 

<asp:Repeater ID="ArticleRepeater" runat="server" EnableViewState="false" OnItemDataBound="ArticleRepeater_ItemDataBound"> 
<ItemTemplate> 
        
<asp:HyperLink ID="SubjectHyperLink" runat="server"></asp:HyperLink> 
</ItemTemplate> 
</asp:Repeater>

然后在ItemDataBound中高亮 
protected void ArticleRepeater_ItemDataBound2(object sender, RepeaterItemEventArgs e)
{
    
// DataGrid在这里可能不是一样,反正找到引用,自己研究一下代码 
    DataRowView rowView = (DataRowView) e.Item.DataItem;
    
string subject = ((string) rowView["Subject"]).Trim();
    
if (IsSearchMode) // 是否搜索模式,这个你自己作啊。 
    {
        
string keyword = SubjectTextBox.Text.Trim();
        subject 
= HighlightKeyword(subject, keyword); // 这里高亮 
    }
    
// 复用ID找到显示主题的控件,然后设置Text属性。 
    HyperLink link = (HyperLink) e.Item.FindControl("SubjectHyperLink");
    link.Text 
= subject;
}

// 不区分大小写高亮的。 
static string HighlightKeyword(string str, string keyword)
{
    
int index;
    
int startIndex = 0;
    
string highlightBegin = "<span style='background-color:#FFEE62'>";
    
string highlightEnd = "</span>";
    
int length = highlightBegin.Length + keyword.Length;
    
int lengthHighlight = length + highlightEnd.Length;

    
while ((index = str.IndexOf(keyword, startIndex, StringComparison.OrdinalIgnoreCase)) > -1)
    {
        str 
= str.Insert(index, highlightBegin).Insert(index + length, highlightEnd);
        startIndex 
= index + lengthHighlight;
    }

    
return str;
}

posted on 2007-08-14 23:03  kyovcs  阅读(825)  评论(1编辑  收藏  举报

导航