C# TreeView控件动态绑定数据库

想要形成这种效果的话,首先在数据里面建一张表

create table treedata (id number, context varchar2(50), parentid number);

id:当前的id,context当前节点的值文本,parentid代表当前节点的父节点id

insert into treedata values(1, '所有部门', 0);

insert into treedata values(2, '人事部', 1);

insert into treedata values(3, '财务部', 1);

insert into treedata values(4, '生产部', 1);

insert into treedata values(5, '车间一', 4);

insert into treedata values(6, '车间二', 4);

insert into treedata values(7, '车间三', 4);

insert into treedata values(8, '商务部', 1);


再用递归根据数据库查询的值动态绑定treeView


public void AddTree(int ParentID, TreeNode pNode)
        {
            string sql = "select id, context, parentid from treedata";
            DataSet ds = OracleHelper.ExecuteDataset(OracleHelper.Con, CommandType.Text, sql, null);
            TreeNode tn1 = new TreeNode();
            DataView dvTree = new DataView(ds.Tables[0]);
            //过滤ParentID,得到当前的所有子节点
            dvTree.RowFilter = "[PARENTID] = " + ParentID;
            foreach (DataRowView Row in dvTree)
            {
                if (pNode == null)
                {    //'?添加根节点

                    tn1.Text = Row["ConText"].ToString();
                    treeView1.Nodes.Add(tn1);
                    tn1.ExpandAll();
                    AddTree(Int32.Parse(Row["ID"].ToString()), tn1);    //再次递归
                }
                else
                {   //添加当前节点的子节点
                    TreeNode tn2 = new TreeNode();
                    tn2.Text = Row["ConText"].ToString();
                    pNode.Nodes.Add(tn2);
                    tn1.ExpandAll();
                    AddTree(Int32.Parse(Row["ID"].ToString()), tn2);    //再次递归
                }
            }
            treeView1.ExpandAll();
        }

应用:

private void 人员资料管理_Load(object sender, EventArgs e)
        {
            AddTree(0, (TreeNode)null);
            treeView1.ExpandAll();//默认展开所有节点
            this.toolStripComboBox1.SelectedIndex = 0;
        }

就可以了。。。。


转载于:https://www.cnblogs.com/tqj-zyy/archive/2012/06/01/4559857.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值