New to Telerik UI for WinFormsStart a free 30-day trial

Highlight Filtering Results by using HTML-like text formatting in RadListView

Updated over 6 months ago

Environment

Product VersionProductAuthor
2020.1.113RadListView for WinFormsNadya Karaivanova

Description

This tutorial demonstrates how to highlight text results both backcolor and forecolor when filtering in RadListView by using HTML-like text formatting approach.

highlight-filtering-results-with-html.png

Solution

First, I would like to note that HTML-like text formatting uses uses GDI+ to measure and render the text. You can find more information about text rendering here.

The desired text highlight effect can be achieved by subscribing to the VisualItemFormatting event that provides a convenient way for customizing the items appearance. In this event you have access to the ListViewDataItem via the VisualItem.Data property. Then, you can separate the text to a small parts by the searched symbol/s. Finally, you can use the HTML-like text formatting to apply a specific look of the text parts accordingly.

A full code snippet is illustrated below:

C#

public RadForm1()
{
    InitializeComponent();
    this.radListView1.UseCompatibleTextRendering = true;

    radListView1.EnableFiltering = true;
    this.radTextBoxControl1.TextChanged += this.radTextBoxControl1_TextChanged;
    this.radListView1.VisualItemFormatting += this.RadListView1_VisualItemFormatting;
}

string searchedValue;
private void RadListView1_VisualItemFormatting(object sender, ListViewVisualItemEventArgs e)
{
    ListViewDataItem data = e.VisualItem.Data as ListViewDataItem;
    if (data != null && searchedValue != null)
    {
        string dataText = data.Text;
        if (dataText.Contains(searchedValue))
        {
            string firstPart = dataText.Substring(0, dataText.IndexOf(searchedValue));
            int startFormatting = dataText.IndexOf(searchedValue) + searchedValue.Length;
            string secondPart = dataText.Substring(startFormatting, dataText.Length - startFormatting);

            e.VisualItem.Text = String.Format(@"<html>" + firstPart + "<span style=\"color: white\"><span style=\"background-color:red\">" + searchedValue + "</span><span style=\"color: black\">" + secondPart) + "</span></html>";
        }
    }
}
private void radTextBoxControl1_TextChanged(object sender, EventArgs e)
{
    searchedValue = (sender as RadTextBoxControl).Text;
    if (searchedValue != null)
    {
        FilterDescriptor valueFilter = new FilterDescriptor(this.radListView1.DisplayMember, FilterOperator.Contains, searchedValue);
        this.radListView1.FilterDescriptors.Add(valueFilter);
    }
}

   
In this article
EnvironmentDescriptionSolution
Not finding the help you need?
Contact Support