部門表
bumenId 部門
1 産品研發部
2 工程項目部
3 行政部
4 市場部
使用者表
userId 使用者 bumenId
1 張三 1
2 李四 1
3 王五 2
4 餘六 2
5 田七 3
6 朱八 3
7 葉九 4
8 姚個 4
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace CSDNDemoTest
{
public partial class Form1 : Form
public Form1()
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
DataSet ds_Department = getDataSet("部門表");
DataSet ds_Employees = getDataSet("使用者表");
foreach (DataRow dr in ds_Department.Tables[0].Rows)
//部門表綁定,作為一級層次
TreeNode tn_origine = new TreeNode();
tn_origine.Text = dr["部門"].ToString();
this.treeView1.Nodes.Add(tn_origine);
//使用者表綁定
DataRow[] dr_arr = ds_Employees.Tables[0].Select("bumenId="+int.Parse(dr["bumenId"].ToString()));
if (dr_arr.Length > 0)
foreach (DataRow dr_sub in dr_arr)
TreeNode tn_sub = new TreeNode();
tn_sub.Text = dr_sub["使用者"].ToString();
tn_origine.Nodes.Add(tn_sub);
//擷取資料集
public DataSet getDataSet(string tableName)
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection("Data Source=localhost;uid=sa;pwd=saiyang;Database=CSDN"))
con.Open();
string strSQL = "select * from "+tableName;
using (SqlDataAdapter sda = new SqlDataAdapter(strSQL, con))
sda.Fill(ds);
return ds;
輸出結果如下:

二、另一種方式,資料表結果如下圖: