需要添加到TreeView 中的數據在數據庫中的存儲表:
ID 為主鍵,PID 表明數據之間的關系。
/// <summary> /// 生產樹的代碼; /// </summary> /// <param name="node"> 根節點</param> /// <param name="id">主鍵</param> private void CreateTwo(TreeNode node, int id) { string strSql = "select * from TableTest where PID = " + id; DataTable dt = SqlClass.GetTable(strSql); if (id == 0) // id = 0 是根節點 { for (int i = 0; i < dt.Rows.Count; i++) { TreeNode nd = new TreeNode(); nd.Text = dt.Rows[i]["Name"].ToString(); CreateTwo(nd, Convert.ToInt32(dt.Rows[i]["id"].ToString())); tvwTwo.Nodes.Add(nd); } } else { for (int i = 0; i < dt.Rows.Count; i++) { TreeNode Tnode = new TreeNode(); Tnode.Text = dt.Rows[i]["Name"].ToString(); CreateTwo(Tnode, Convert.ToInt32(dt.Rows[i]["id"].ToString())); node.Nodes.Add(Tnode); } } } 則個代碼比較簡單 只需要查詢一個數據表。
生成結果: