[WinForm Detailed Tutorial 8] TreeView Control in WinForm

TreeViewThe control is used to display hierarchical data. It displays information in a tree structure. Each node can have one or more child nodes. TreeView Control allows users to view complex hierarchical information in expandable and collapsible forms.

TreeViewbasic knowledge

Attributes

  • Nodes: A TreeNodeCollection that contains the root node of the control.
  • SelectedNode: Get or set the currently selected TreeNode.
  • CheckBoxes: Determines whether to display a checkbox next to each tree node.
  • ShowPlusMinus: Determines whether to display plus and minus signs for expanding and collapsing tree nodes.
  • ShowLines: Determines whether to display connecting lines between tree nodes.

method

  • BeginUpdate(): Pauses the drawing control, which can be used to avoid redrawing and improve performance when adding a large number of nodes.
  • EndUpdate(): Resumes the normal drawing control, used in conjunction with BeginUpdate().
  • CollapseAll(): Collapse all tree nodes.
  • ExpandAll(): Expand all tree nodes.
  • GetNodeAt(): Returns the TreeNode located at the specified point.

event

  • AfterCheck / BeforeCheck: After the node’s checkbox is selected or unchecked by the user/ happened before.
  • AfterSelect / BeforeSelect: Occurs after/before selecting a node.
  • AfterCollapse / BeforeCollapse: Occurs after/before the node is collapsed.
  • AfterExpand / BeforeExpand: Occurs after/before the node is expanded.
  • NodeMouseClick: Occurs when the mouse clicks on a TreeNode.

Node introduction - TreeNode

  • Name: The unique identifier of the node.
  • Text: The text displayed by the node.
  • Nodes: A collection of child nodes.

Dynamically load menu table

  • The relationship between nodes and sub-nodes is stored in the database, but the hierarchical relationship is not obvious.
  • The process of dynamically loading data into the TreeView control:
    1. Get table data from database.
    2. Nodes are created using a recursive method and added to the TreeView.
    3. Call methods to create and display hierarchical data in a TreeView.

Check processing of TreeView nodes

  • When the parent node is checked or unchecked, the status of all child nodes changes accordingly.
  • If any child node is checked, the parent node should also be checked.
  • All child nodes are unchecked, and neither are the parent nodes.

TreeViewCase presentation

Case number one:

namespace WinFormsTest
{
    public partial class frmTreeView : Form
    {
        public frmTreeView()
        {
            InitializeComponent();
        }

        private void frmTreeView_Load(object sender, EventArgs e)
        {
            TreeView fileTree = new TreeView();
            // 单独设置 Width 和 Height
            fileTree.Width = 200;  // 设置宽度为200像素
            fileTree.Height = 600; // 设置高度为400像素

            // 或者使用 Size 属性同时设置宽度和高度
            fileTree.Size = new Size(200, 300); // 宽度200像素,高度400像素
            // 开始更新节点,防止在添加节点时进行重绘
            fileTree.BeginUpdate();
            TreeNode rootNode = new TreeNode("我的电脑");
            fileTree.Nodes.Add(rootNode);
            // 添加几个文件夹作为子节点
            TreeNode documentsNode = new TreeNode("文档");
            TreeNode picturesNode = new TreeNode("图片");
            TreeNode musicNode = new TreeNode("音乐");
            TreeNode videoNode = new TreeNode("视频");
            rootNode.Nodes.Add(documentsNode);
            rootNode.Nodes.Add(picturesNode);
            rootNode.Nodes.Add(musicNode);
            rootNode.Nodes.Add(videoNode);
            // 完成节点添加后,恢复控件的绘制
            fileTree.EndUpdate();
            fileTree.AfterSelect += new TreeViewEventHandler(fileTree_AfterSelect);
            this.Controls.Add(fileTree);
        }
        private void fileTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Text != "我的电脑")
            {
                // 当用户选择一个节点时,显示选中节点的信息
                MessageBox.Show("选中的文件夹: " + e.Node.Text);
            }
        }
    }
}

Effect:

Animation 10

Case 2:

using System.Data;
using WinFormsTest.Helper;
namespace WinFormsTest
{
    public partial class frmTreeView2 : Form
    {
        public frmTreeView2()
        {
            InitializeComponent();
        }

        private void frmTreeView2_Load(object sender, EventArgs e)
        {
            treeView1.Nodes.Clear();//清除所有节点
            //1. 获取数据
            DataTable dtMenus = DBHelper.GetDataTable("select Id,MName,ParentId from MenuInfos", 1);
            //3.调用方法,添加节点
            CreateNode(dtMenus, null, 0);
        }

        //2.添加节点(递归)
        private void CreateNode(DataTable dt, TreeNode pNode, int parentId)
        {
            //1.获取要创建的节点数据
            DataRow[] rows = dt.Select("ParentId=" + parentId);
            if (rows.Length > 0)
            {
                foreach (DataRow r in rows)
                {
                    //2.新建子节点
                    TreeNode node = new TreeNode();
                    node.Name = r["Id"].ToString();
                    node.Text = r["MName"].ToString();
                    //3.直接添加到TreeView Nodes  还是添加指定节点的Nodes里? 
                    if (pNode != null)
                        pNode.Nodes.Add(node);
                    else
                        treeView1.Nodes.Add(node);
                    //4.判断当前节点下有没有子节点
                    //这个是递归,直到rows为0即当前节点没有子节点时结束递归
                    CreateNode(dt, node, int.Parse(node.Name));
                }
            }
        }
        
/添加父子勾选关联功能        
//1.父节点勾选或取消,它的所有子节点与它一致  
//2.只要有一个子节点勾选,父节点就勾选
//	子节点全部不勾选,父节点就不勾选
        bool isMouseClick = true;
        private void treeView1_NodeMouseClick_1(object sender, TreeNodeMouseClickEventArgs e)
        {
            isMouseClick = false;
            //子节点勾选
            SetChildNodesState(e.Node);
            //父节点勾选
            SetParentNodeState(e.Node);
            isMouseClick = true;
        }
        private void treeView1_AfterCheck_1(object sender, TreeViewEventArgs e)
        {
            if (isMouseClick)
            {
                treeView1.SelectedNode = e.Node; //当前操作节点选中
            }
        }

        //递归处理子节点的勾选
        private void SetChildNodesState(TreeNode node)
        {
            if (node.Nodes.Count > 0)
            {
                foreach (TreeNode n in node.Nodes)
                {
                    n.Checked = node.Checked;
                    SetChildNodesState(n);
                }
            }
        }
        private void SetParentNodeState(TreeNode node)
        {
            TreeNode pNode = node.Parent;//获取父节点
            if (pNode != null)
            {
                bool bl = false;

                foreach (TreeNode n in pNode.Nodes)
                {
                    if (n.Checked)
                    {
                        bl = true;
                        break;
                    }
                }
                pNode.Checked = bl;
                SetParentNodeState(pNode);
            }
        }
    }
}

Effect:

Create a new SQL database

image-20231107192018880

exhibit

Please add image description

After adding the parent-child check association function

Animation 12

[WinForm Detailed Tutorial] How to obtain source code

Insert image description here

Excellent recommendations:
[C# Advanced 1] Array (Array), collection (ArrayList, Queue, Stack, HashList), List
[C# Advanced 8] Serialization and deserialization in C# (binary serialization, XML serialization and JSON serialization) a>

[Advanced C#] Summary of some common knowledge points in C# syntax
[WinForm detailed tutorial 1] Form, Label, TextBox and Button controls, RadioButton and CheckBox, ListBox
[WinForm detailed tutorial three] NumericUpDown, PictureBox, RichTextBox and three Timer controls in WinForm
[WinForm detailed tutorial four] ProgressBar and ImageList in WinForm and ListView control
[WinForm detailed tutorial five] MenuStrip, ContextMenuStrip, ToolStrip, StatusStrip control in WinForm
[WinForm detailed tutorial six] GroupBox and Panel in WinForm , TabControl, SplitContainer control
[C# Advanced] Delegates, events, callback functions, anonymous functions and lambda expressions in C#

If you are interested in the intelligent construction major, or are a student, teacher or practitioner in a related field, you are welcome to join us through the WeChat public account [Intelligent Construction Xiaoshuo]!

Insert image description here
Hope it helps, and welcome to follow us. More related content will be updated later!

Guess you like

Origin blog.csdn.net/QH2107/article/details/134277456