不管是webform仍是winform,TreeView都是經常使用功能。使用遞歸方法很方便。html
下面分享一個小實例。node
數據庫中3個字段,分別是:ID,itemType_name,itemType_PIDweb
private void itemType_Load(object sender, EventArgs e) { dataBind(); } private void dataBind() { //獲取數據 string sql = "select * from itemType order by itemType_paixu"; DB db = new DB(); string _msg = ""; DataTable DT = db.GetDt(sql, out _msg); // treeView1.Nodes.Clear(); //添加頂節點 TreeNode tempNode = new TreeNode(); tempNode.Text = "商品類別"; tempNode.Name = "0"; treeView1.Nodes.Add(tempNode); // nodeBind(treeView1, DT, "0", tempNode); treeView1.ExpandAll(); // } public void nodeBind(TreeView _treeView, DataTable _dt, string _filter, TreeNode _pNode) { //循環構建樹 string sFilter = "itemType_PID=" + _filter; TreeNode parentNode = _pNode; DataView dv = new DataView(_dt); dv.RowFilter = sFilter; if (dv.Count > 0) { foreach (DataRowView drv in dv) { TreeNode tempNode = new TreeNode(); tempNode.Text = drv["itemType_name"].ToString(); tempNode.Name = drv["ID"].ToString(); if (parentNode != null) parentNode.Nodes.Add(tempNode); else _treeView.Nodes.Add(tempNode); nodeBind(_treeView, _dt, drv["ID"].ToString(), tempNode); } } }
上面這個例子是有固定根節點的,下面這個例子是沒有根節點的,遞歸構建更方便。sql
private void codeitem_Load(object sender, EventArgs e) { dataBind(); } private void dataBind() { //獲取數據 string sql = "select * from codeitem order by codeitem_paixu"; DB db = new DB(); string _msg = ""; DataTable DT = db.GetDt(sql, out _msg); // treeView1.Nodes.Clear(); nodeBind(treeView1, DT, "0", null); treeView1.ExpandAll(); // } public void nodeBind(TreeView _treeView, DataTable _dt, string _filter, TreeNode _pNode) { //循環構建樹 string sFilter = "codeitem_pcode=’" + _filter + "’"; TreeNode parentNode = _pNode; DataView dv = new DataView(_dt); dv.RowFilter = sFilter; if (dv.Count > 0) { foreach (DataRowView drv in dv) { TreeNode tempNode = new TreeNode(); tempNode.Text = drv["codeitem_name"].ToString(); tempNode.Name = drv["ID"].ToString(); if (parentNode != null) parentNode.Nodes.Add(tempNode); else _treeView.Nodes.Add(tempNode); nodeBind(_treeView, _dt, drv["codeitem_code"].ToString(), tempNode); } } }
bubuko.com版權全部,禁止轉載。原地址:【winform,TreeView樹,樹形菜單,bubufx】數據庫