TreeView的使用
用于显示多级层次关系
每一项是一个节点,也就是一个Node,是一个TreeNode节点,Nodes是该控件节点的集合。
selectedNode用户选中的节点,如果没有选中则为null
1. 当选中后,光标离开依然是选中状态时,则应该修改HideSelection
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace TreeView的使用 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(treeView1.SelectedNode.Text); } private void button2_Click(object sender, EventArgs e) { //Nodes是第一级节点的集合,在第一级节点添加,即根节点 //treeView1.Nodes.Add() //在第一个根节点的下一级添加 //treeView1.Nodes[0].Nodes.Add("aaa"); //根据用户选择添加信息 if(treeView1.SelectedNode != null) { treeView1.SelectedNode.Nodes.Add(textBox1.Text); } else { treeView1.Nodes.Add(textBox1.Text); } } private void Form1_Load(object sender, EventArgs e) { //展开所有节点 treeView1.ExpandAll(); } private void button3_Click(object sender, EventArgs e) { treeView1.CollapseAll(); } private void button4_Click(object sender, EventArgs e) { treeView1.ExpandAll(); } private void button5_Click(object sender, EventArgs e) { treeView1.SelectedNode.Collapse(); } private void button6_Click(object sender, EventArgs e) { //当前节点的的下一级节点 treeView1.SelectedNode.Expand(); //当前节点的所有节点 //treeView1.SelectedNode.ExpandAll(); } private void button7_Click(object sender, EventArgs e) { treeView1.SelectedNode.Remove(); } private void button8_Click(object sender, EventArgs e) { treeView1.SelectedNode.Text = textBox2.Text; } private void button9_Click(object sender, EventArgs e) { string str = "选中的节点:\n"; foreach(TreeNode tn in treeView1.Nodes[0].Nodes[0].Nodes) { if(tn.Checked) str += tn.Text+"\n"; } MessageBox.Show(str); } private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { } private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { foreach(TreeNode tn in e.Node.Nodes) { tn.Checked = e.Node.Checked; } } } }