首先你没把部门节点之间的父子关系说清楚,别人刚看到会一头雾水!我想你表后面那两个字段应该表示其部门id和其父部门id
你DAL跟BLL这样设计有点问题
我想应该这样设计会比较好
DAL
public DataTable GetData()
{
string sql = "select * from T_department";
DataTable dt = SqlHelper.ExecuteDataTable(sql);
//这你要先定义好这个ExecuteDataTable这个方法,连接数据库并查找表并返回dataTable的方法
return dt;
}
Model
public class TreeModel
{
public string D_Cid
{ get; set; }
public int D_Id
{ get; set; }
public string D_Name { get; set; }
public int D_Pid { get; set; }
//
public List<TreeModel> TreeModels { get; set; }
}
BLL
using *.DAL;//先添加该DAL层项目
public class TreeBLL
{
public List<TreeModel> GetAllTree()
{
TreeDAL dal = new TreeDAL();
List<TreeModel> list = new List<TreeModel>();
DataTable dt=dal.GetData();
for(int i = 0; i < dt.Rows.Count; i++)
{
//暂且认为表T_department最后两列的字段名分别为d_id和d_pid
if (Convert.ToInt32(dt.Rows[i]["PerentID"]) == 0)
{
TreeModel tm = new TreeModel();
tm.D_Cid = dr["d_cid"].ToString();
tm.D_Id = dr["d_id"].ToString();
tm.D_Name = dr["d_name"].ToString();
tm.D_Pid = dr["d_pid"].ToString();
for(int j = 0; j < dt.Rows.Count; j++)
{
if(Convert.ToInt32(dt.Rows[j]["d_pid"]) == Convert.ToInt32(dt.Rows[i]["d_id"]))
{
TreeModel tm1 = new TreeModel();
tm1.D_Cid = dr["d_cid"].ToString();
tm1.D_Id = dr["d_id"].ToString();
tm1.D_Name = dr["d_name"].ToString();
tm1.D_Pid = dr["d_pid"].ToString();
tm.TreeModels.add(tm1);
for(int k = 0; k < dt.Rows.Count; k++)
{
if(Convert.ToInt32(dt.Rows[k]["d_pid"]) == Convert.ToInt32(dt.Rows[j]["d_id"]))
{
TreeModel tm2 = new TreeModel();
tm2.D_Cid = dr["d_cid"].ToString();
tm2.D_Id = dr["d_id"].ToString();
tm2.D_Name = dr["d_name"].ToString();
tm2.D_Pid = dr["d_pid"].ToString();
tm1.TreeModels.add(tm2);
for(int m = 0; m< dt.Rows.Count; m++)
{
TreeModel tm3 = new TreeModel();
tm3.D_Cid = dr["d_cid"].ToString();
tm3.D_Id = dr["d_id"].ToString();
tm3.D_Name = dr["d_name"].ToString();
tm3.D_Pid = dr["d_pid"].ToString();
tm2.TreeModels.add(tm3);
}
}
}
}
}
list.add(tm);
}
return list;
}
}
UI层
List<TreeModel> list=new GetAllTree();
foreach(TreeModel tm in list)
{
treeview.node.add(tm);
if(tm.TreeModels!=null)
{
foreach(TreeModel tm1 in tm.TreeModels)
tree.node.node.add(tm1);
if(tm1.TreeModels!=null)
{
foreach(TreeModel tm2 in tm1.TreeModels)
tree.node.node.node.add(tm2);
}
}
}