部门表
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;
输出结果如下:

二、另一种方式,数据表结果如下图: