在C#中,為TreeView控件實(shí)現(xiàn)搜索功能需要以下幾個(gè)步驟:
以下是一個(gè)簡(jiǎn)單的示例:
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();
// 初始化數(shù)據(jù)源
_persons.Add(new Person("張三"));
_persons.Add(new Person("李四"));
_persons.Add(new Person("王五"));
_persons.Add(new Person("趙六"));
// 綁定數(shù)據(jù)源到TreeView
treeView1.DataSource = _persons;
treeView1.DisplayMemberKeyProperty = "Name";
// 搜索框
searchTextBox.TextChanged += SearchTextBox_TextChanged;
}
private void SearchTextBox_TextChanged(object sender, EventArgs e)
{
// 根據(jù)搜索關(guān)鍵字過(guò)濾數(shù)據(jù)源
string keyword = searchTextBox.Text;
_filteredPersons.Clear();
foreach (var person in _persons)
{
if (person.Name.Contains(keyword))
{
_filteredPersons.Add(person);
}
}
// 更新TreeView的數(shù)據(jù)源
treeView1.DataSource = _filteredPersons;
treeView1.Refresh();
}
}
public class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)包含四個(gè)Person對(duì)象的List