Using the TreeView control in C#
The TreeView control in C# is used to display hierarchical structured data, typically used to display data in a tree-like structure. Here are the instructions for using the TreeView control:
- Add a TreeView control to the form:
Locate the TreeView control in the toolbox of Visual Studio, and drag it onto the form. - Add tree nodes:
You can add tree nodes using the Nodes property of the TreeView control. For example, use TreeView.Nodes.Add() method to add a root node, and use the node’s Nodes.Add() method to add a child node.
// 添加根节点
TreeNode rootNode = treeView1.Nodes.Add("Root Node");
// 添加子节点
TreeNode childNode = rootNode.Nodes.Add("Child Node");
- To set the attributes of a tree node, you can use the Text property to set the text content of the node, and the ImageIndex property to set the icon index of the node.
// 设置节点文本内容
rootNode.Text = "Root Node";
// 设置节点图标索引
rootNode.ImageIndex = 0;
- Handling node selection events:
One option is to use the AfterSelect event of the TreeView control to handle node selection events. For example, displaying the text content of the selected node.
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
TreeNode selectedNode = e.Node;
MessageBox.Show(selectedNode.Text);
}
- Expand and collapse nodes:
You can use the Expand() and Collapse() methods of the node to expand and collapse nodes.
// 展开节点
rootNode.Expand();
// 折叠节点
rootNode.Collapse();
- To set the checkbox status of a node:
In the TreeView control, nodes can have different checkbox statuses, and you can use the Checked property of the node to set the checkbox status.
// 设置节点为勾选状态
rootNode.Checked = true;
- Delete node:
You can remove a node using the Nodes.Remove() method of the TreeView control.
// 删除节点
treeView1.Nodes.Remove(rootNode);
These are the basic usage methods of the TreeView control, which can be further customized and extended according to actual needs.