private DataTable dt = null;
private void Form1_Load(object sender, EventArgs e)
{
//加载数据表
dt = DB.GetTable("select deptId,parentId,deptName from dept");
dataGridView1.DataSource = dt;
BindRoot();
}
//获取根节点
private void BindRoot()
{
//从dt表中查询出parentId='ABC'的行
DataRow[] ro = dt.Select("parentId='ABC'");
foreach (DataRow dr in ro)
{
//if (dr["parentId"].ToString() == "ABC")
//{
TreeNode node = new TreeNode();
node.Tag = dr;
node.Text = dr["deptName"].ToString();
treeView1.Nodes.Add(node);
AddChild(node);
//}
}
}
//绑定子节点
private void AddChild(TreeNode node)
{
DataRow dr2 = (DataRow)node.Tag;//获取与根节点关联的数据行
string pId = dr2["deptId"].ToString();//获取根节点的deptId
//从dt表中查询出parentId=deptId的节点
DataRow[] rows = dt.Select("parentId='"+pId+"'");
if (rows.Length == 0)
return;
foreach (DataRow drow in rows) //再次遍历,添加子节点
{
TreeNode node3 = new TreeNode();
node3.Tag = drow;
node3.Text = drow["deptName"].ToString();
node.Nodes.Add(node3);
//递归
AddChild(node3);
}
}