在C#中,为TreeView控件实现搜索功能需要以下几个步骤:
以下是一个简单的示例:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TreeViewSearchExample
{
public partial class Form1 : Form
{
private List<Person> _persons = new List<Person>();
private List<Person> _filteredPersons = new List<Person>();
public Form1()
{
InitializeComponent();
// 初始化数据源
_persons.Add(new Person("张三"));
_persons.Add(new Person("李四"));
_persons.Add(new Person("王五"));
_persons.Add(new Person("赵六"));
// 绑定数据源到TreeView
treeView1.DataSource = _persons;
treeView1.DisplayMemberKeyProperty = "Name";
// 搜索框
searchTextBox.TextChanged += SearchTextBox_TextChanged;
}
private void SearchTextBox_TextChanged(object sender, EventArgs e)
{
// 根据搜索关键字过滤数据源
string keyword = searchTextBox.Text;
_filteredPersons.Clear();
foreach (var person in _persons)
{
if (person.Name.Contains(keyword))
{
_filteredPersons.Add(person);
}
}
// 更新TreeView的数据源
treeView1.DataSource = _filteredPersons;
treeView1.Refresh();
}
}
public class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
}
在这个示例中,我们创建了一个包含四个Person对象的List