您的位置:首页 > 编程语言 > C#

C# 向 ListView 控件添加搜索功能

2011-07-08 10:48 351 查看
ListView 控件中使用大型的项列表时,经常会希望向用户提供搜索功能。ListView 控件以两种不同的方式提供此功能:文本匹配和位置搜索。 FindItemWithText 方法允许在处于列表或详细信息视图的 ListView 上执行文本搜索,要求给定搜索字符串和可选的起始和结束索引。而 FindNearestItem 方法允许在处于图标或平铺视图的 ListView 中查找项,要求给定一组 x 坐标和 y 坐标以及一个搜索方向。

使用文本查找项

创建一个 ListViewView 属性设置为 Details 或 List,然后用项填充该 ListView

调用 FindItemWithText 方法,向其传递要查找的项的文本。

下面的代码示例演示如何创建基本 ListView,用项进行填充并使用由用户输入的文本来在列表中查找项。

private ListView textListView = new ListView();
private TextBox searchBox = new TextBox();
private void InitializeTextSearchListView()
{
searchBox.Location = new Point(10, 60);
textListView.Scrollable = true;
textListView.Width = 80;
textListView.Height = 50;

// Set the View to list to use the FindItemWithText method.
textListView.View = View.List;

// Populate the ListViewWithItems
textListView.Items.AddRange(new ListViewItem[]{
new ListViewItem("Amy Alberts"),
new ListViewItem("Amy Recker"),
new ListViewItem("Erin Hagens"),
new ListViewItem("Barry Johnson"),
new ListViewItem("Jay Hamlin"),
new ListViewItem("Brian Valentine"),
new ListViewItem("Brian Welker"),
new ListViewItem("Daniel Weisman") });

// Handle the TextChanged to get the text for our search.
searchBox.TextChanged += new EventHandler(searchBox_TextChanged);

// Add the controls to the form.
this.Controls.Add(textListView);
this.Controls.Add(searchBox);

}

private void searchBox_TextChanged(object sender, EventArgs e)
{
// Call FindItemWithText with the contents of the textbox.
ListViewItem foundItem =
textListView.FindItemWithText(searchBox.Text, false, 0, true);
if (foundItem != null)
{
textListView.TopItem = foundItem;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: