How to: Highlight the Text Placed Inside the DataItem Template During a Search

  • 3 minutes to read

Search results contained in templates are not highlighted by default, but you can highlight them manually. The following example wraps the search results in a <span> tag with the "dxcvHL" class. Note that this is a basic example that illustrates how to process simple requests. If you create composite criteria, it is necessary to perform additional operations to parse the search text.

View Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;

public partial class _Default : System.Web.UI.Page
{
    protected void label1_DataBound(object sender, EventArgs e)
    {
        ASPxLabel label = sender as ASPxLabel;
        label.Text = HighlightSearchText(label.Text, ASPxCardView1.SearchPanelFilter);
    }


    public static string HighlightSearchText(string source, string searchText)
    {
        if (string.IsNullOrWhiteSpace(searchText))
            return source;
        var regex = new Regex(Regex.Escape(searchText), RegexOptions.IgnoreCase);
        if (regex.IsMatch(source))
            return string.Format("<span>{0}</span>", regex.Replace(source, "<span class='dxcvHL'>$0</span>"));
        return source;
    }
}