日期:2014-05-18  浏览次数:21020 次

C# winform treeview的子节点中可以添加控件么?
强烈强烈请求知道的人说一下下


我在TreeView的字节点当中,能不能添加一个控件
类似

  -- --A(父结点)
  B(子结点) X(button)-控件

然后能X控件的事件控制子节点的删除。。


------解决方案--------------------
大同小异吧

C# code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace WindowsApplication217
{
    public partial class Form1 : Form
    {
        TreeView TV = new TreeView();

        public Form1()
        {
            InitializeComponent();

            TV.Parent = this;
            TV.Dock = DockStyle.Fill;
            TV.ItemHeight = 30;

            TreeNode Root = TV.Nodes.Add("根");

            AddDeleteButtonChildNode(Root, "1");
            AddDeleteButtonChildNode(Root, "2");
            AddDeleteButtonChildNode(Root, "3");

            TV.AfterExpand += new TreeViewEventHandler(TV_AfterExpand);
            TV.AfterCollapse += new TreeViewEventHandler(TV_AfterCollapse);
        }

        void TV_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            ChangeDeleteButtonVisible(e.Node, false);
        }

        void TV_AfterExpand(object sender, TreeViewEventArgs e)
        {
            ChangeDeleteButtonVisible(e.Node, true);
        }

        void ChangeDeleteButtonVisible(TreeNode ParentNode, bool Visible)
        {
            foreach (TreeNode ChildNode in ParentNode.Nodes)
            {
                Button B = (Button)ChildNode.Tag;
                B.Location = ChildNode.Bounds.Location;
                B.Left += ChildNode.Bounds.Width;   
                B.Visible = Visible;
            }
        }

        void AddDeleteButtonChildNode(TreeNode ParentNode, String Text)
        {
            TreeNode Node = ParentNode.Nodes.Add(Text);

            Button B = new Button();
            B.Parent = TV;
            B.Text = "删除";
            B.Visible = false;
            B.Click += new EventHandler(B_Click);

            B.Tag = Node;
            Node.Tag = B;
        }

        void B_Click(object sender, EventArgs e)
        {
            Button B = (Button)sender;
            TreeNode Node = (TreeNode)B.Tag;
            TreeNode ParentNode = Node.Parent; 

            B.Dispose(); 
            Node.Remove();

            ChangeDeleteButtonVisible(ParentNode, true); // 刷新重新定位按钮
        }
    }
}