您好,欢迎来到刀刀网。
搜索
您的当前位置:首页winform中的TreeView的数据绑定

winform中的TreeView的数据绑定

来源:刀刀网
winform中的TreeView的数据绑定

#region 绑定TreeView ///

/// 绑定TreeView(利⽤TreeNode) ///

/// TreeNode(TreeView的⼀个节点) /// ⽗id的值 /// 数据库 id 字段名 /// 数据库 ⽗id 字段名 /// 数据库 ⽂本 字段值

protected void Bind_Tv(DataTable dt, TreeNode p_Node, string pid_val, string id, string pid, string text) {

DataView dv = new DataView(dt);//将DataTable存到DataView中,以便于筛选数据 TreeNode tn;//建⽴TreeView的节点(TreeNode),以便将取出的数据添加到节点中

//以下为三元运算符,如果⽗id为空,则为构建“⽗id字段 is null”的查询条件,否则构建“⽗id字段=⽗id字段值”的查询条件 string filter = string.IsNullOrEmpty(pid_val) ? pid + \" is null\" : string.Format(pid + \"='{0}'\", pid_val); dv.RowFilter = filter;//利⽤DataView将数据进⾏筛选,选出相同 ⽗id值 的数据 foreach (DataRowView row in dv) {

tn = new TreeNode();//建⽴⼀个新节点(学名叫:⼀个实例) if (p_Node == null)//如果为根节点 {

tn.Name = row[id].ToString();//节点的Value值,⼀般为数据库的id值 tn.Text = row[text].ToString();//节点的Text,节点的⽂本显⽰ TreeView1.Nodes.Add(tn);//将该节点加⼊到TreeView中

Bind_Tv(dt, tn, tn.Name, id, pid, text);//递归(反复调⽤这个⽅法,直到把数据取完为⽌) }

else//如果不是根节点 {

tn.Name = row[id].ToString();//节点Value值 tn.Text = row[text].ToString();//节点Text值

p_Node.Nodes.Add(tn);//该节点加⼊到上级节点中 Bind_Tv(dt, tn, tn.Name, id, pid, text);//递归 } } }

///

/// 绑定TreeView(利⽤TreeNodeCollection) ///

/// TreeNodeCollection(TreeView的节点集合) /// ⽗id的值 /// 数据库 id 字段名 /// 数据库 ⽗id 字段名 /// 数据库 ⽂本 字段值

private void Bind_Tv(DataTable dt, TreeNodeCollection tnc, string pid_val, string id, string pid, string text) {

DataView dv = new DataView(dt);//将DataTable存到DataView中,以便于筛选数据 TreeNode tn;//建⽴TreeView的节点(TreeNode),以便将取出的数据添加到节点中

//以下为三元运算符,如果⽗id为空,则为构建“⽗id字段 is null”的查询条件,否则构建“⽗id字段=⽗id字段值”的查询条件 string filter = string.IsNullOrEmpty(pid_val) ? pid + \" is null\" : string.Format(pid + \"='{0}'\", pid_val); dv.RowFilter = filter;//利⽤DataView将数据进⾏筛选,选出相同 ⽗id值 的数据 foreach (DataRowView drv in dv) {

tn = new TreeNode();//建⽴⼀个新节点(学名叫:⼀个实例)

tn.Name = drv[id].ToString();//节点的Value值,⼀般为数据库的id值 tn.Text = drv[text].ToString();//节点的Text,节点的⽂本显⽰ tnc.Add(tn);//将该节点加⼊到TreeNodeCollection(节点集合)中

Bind_Tv(dt, tn.Nodes, tn.Name, id, pid, text);//递归(反复调⽤这个⽅法,直到把数据取完为⽌) } }

#endregion

绑定代码:

Bind_Tv(datatable,TreeView1.Nodes, null, \"id字段\", \"⽗id字段\", \"名称字段\");

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- gamedaodao.com 版权所有 湘ICP备2022005869号-6

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务