递归构造treeview树形结构

1、首先数据库: f_id 项目ID号 ,f_front 父ID号 ,f_name名称,f_type类型,f_layer所处层,f_order 同层的顺序号;(f_layer,f_order不要也可,这里我主要是需要同层排序才用到)

2、然后“select f_id,f_front,f_name,f_type from data”取得DataSet数据集dsFrame;treeview 名称设为tvDept

3、写函数 构建treeveiw树形:

public void AddTree(int ParentID, TreeNode pNode)
               {
                   DataView dvTree = new DataView(dtTree); //就是dtTree = dsFrame.Tables[0];
                   string Fstr = "[f_front]          =          " + ParentID;      
                   dvTree.RowFilter = Fstr;
                   foreach (DataRowView Row in dvTree)
                   {
                       TreeNode Node = new TreeNode();
                       if (pNode == null)                  //处理主节点
                       {    
                           Node.Name = Row["f_id"].ToString(); //这里+了2个值分别到Name和Text,可随便
                           Node.Text = Row["f_name"].ToString();
                           if (Row["f_type"].ToString() == "岗位") //这个不要也可以,主要为了不同类型显示不同图标
                           {
                               Node.ImageIndex = 1;
                               Node.SelectedImageIndex=1;
                           }
                           else
                           {
                               Node.ImageIndex = 0;
                               Node.SelectedImageIndex=0;
                           }
                           tvDept.Nodes.Add(Node);    //加入
                           AddTree(Int32.Parse(Row["f_id"].ToString()), Node); //递归
                       }
                       else //处理子节点

                       {      
                           Node.Name = Row["f_id"].ToString();
                           Node.Text = Row["f_name"].ToString();
                           if (Row["f_type"].ToString() == "岗位")
                           {
                               Node.ImageIndex = 1;
                               Node.SelectedImageIndex = 1;
                           }
                           else
                           {
                               Node.ImageIndex = 0;
                               Node.SelectedImageIndex=0;
                           }
                           pNode.Nodes.Add(Node);                    
                           AddTree(Int32.Parse(Row["f_id"].ToString()), Node);
                       }
                   }
               }

4、调用方法

AddTree(0, (TreeNode)null);    //0就是处于最高级其f_front=0,数据库里1为顶层那就是1,这个随便

最好+一句           tvDept.ExpandAll(); 展开所有项。

posted on 2009-05-13 17:00  洞幺人生  阅读(410)  评论(1编辑  收藏  举报