在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