Owl's Blog on .NET development

Component Owl codes Better ListView control all night so you don't have to.

Search Filtering in Better ListView

Search Filtering

Search Filtering with highlight

There are few ways of making searching in large list of items more convenient. For example, Better ListView provides Search Highlighting and Item Hiding features that can be used to improve searching. The above animation shows both of these features in action when searching for a word “pear” using keyboard.

The implementation is very simple and involves handling just two events: ItemSearch (raised whenever item is searched, e.g. using keyboard ) and KeyDown:

[csharp gutter=”false” toolbar=”false”]
var listView = new BetterListView();

listView.Items.AddRange(new[] { “apple”, “pear”, “pineapple”, “orange”, “grapefruit”, “cherry”, “avocado” });

listView.ItemSearch += listView_ItemSearch;
listView.KeyDown += listView_KeyDown;
[/csharp]

The ItemSearch event handler finds matching items and sets their visibility accordingly. It also updates the highlighting:

[csharp gutter=”false” toolbar=”false”]
void listView_ItemSearch(object sender, BetterListViewItemSearchEventArgs eventArgs)
{
var listView = (BetterListView)sender;

listView.BeginUpdate();

// update item visibility according to search query string
foreach (var item in listView.Items)
{
bool match = item.Text.Contains(eventArgs.QueryString);

if (match)
{
item.Visible = true;

item.SearchHighlight = new BetterListViewSearchHighlight(
0,
item.Text.IndexOf(eventArgs.QueryString, StringComparison.Ordinal),
eventArgs.QueryString.Length);
}
else
{
item.Visible = false;
}
}

listView.EndUpdate();
}
[/csharp]

Finally, the KeyDown event handler resets the view when Escape key is pressed (all items are made visible and the highlight is removed):

[csharp gutter=”false” toolbar=”false”]
void listView_KeyDown(object sender, KeyEventArgs e)
{
var listView = (BetterListView)sender;

listView.BeginUpdate();

if (e.KeyCode == Keys.Escape)
{
// remove search highlight
//NOTE: we could use BetterListView.RemoveSearchHighlight() but this applies to visible items only and some items are hidden at the time
foreach (var item in listView.Items)
{
item.SearchHighlight = BetterListViewSearchHighlight.Empty;
}

// make all items visible
foreach (var item in listView.Items)
{
item.Visible = true;
}

// mark the key as handled
e.Handled = true;

// suppress KeyPress event to prevent ItemSearch from happening
e.SuppressKeyPress = true;
}

listView.EndUpdate();
}
[/csharp]

And that’s it!

2 Responses to “Search Filtering in Better ListView”

  1. mustafa salah says:

    Is this applicable for Express version?

Leave a Reply