部门树的数据表(deptinfo)一共有三个字段,分别为deptid,pid,deptname,这三个字段的意思我不说大家也明白。

部门树的思想:

第一步,查询出所以部门信息。

public DataTable GetAllDeptInfo()
{

           //数据访问采用最原始的ADO.NET技术,现在最好的方式是NHibernate,读者可以自己换
           string connstr = "data source=localhost;Integrated Security=SSPI;initial catalog=Study";//数据库连接字符串有多种,因为我的数据库采用的是Windows认证方式,所以采用Integrated Security=SSPI,若不是则采用uid=用户名;pwd=密码。
            SqlConnection conn=    new SqlConnection(connstr);
            if(conn.State==ConnectionState.Closed)
            conn.Open();
            SqlCommand com = conn.CreateCommand();
            string sql = "select * from DeptInfo";
            DataTable myTable = new DataTable();
            com.CommandText=sql;
            SqlDataAdapter sda = new SqlDataAdapter(com);
            sda.Fill(myTable);   
            if (conn.State == ConnectionState.Open) conn.Close();
            return myTable;

}

protected void Page_Load(object sender, EventArgs e)
{
            DataTable dtParam = GetAllDeptInfo();
            DataTable dtTree = dtParam.Clone();

            //克隆出与dtParam一样架构但没有数据的表
            BuildTree(dtTree, dtParam, 0, "0");//从根部门出发
            DropDownList1.DataSource = dtTree;
            DropDownList1.DataTextField = dtTree.Columns[2].ToString();
            DropDownList1.DataValueField = dtTree.Columns[0].ToString();
            DropDownList1.DataBind();
 }

接下来写递归方法,思想为dtTree加入当前的行,并将非当行前指派到下一递归。

public void BuildTree(DataTable dtTree, DataTable dtParam, int intLevel, string parentid)
{
            intLevel++;
            string strLeftPre = "";

  //设置前辍
       if (intLevel > 1)
            {
                strLeftPre = "|" + strLeftPre.PadLeft(intLevel*2,'-');
            }
            DataTable currTable = new DataTable();
            currTable = dtParam.Clone();//用来记录当前行
         DataTable nextTable = new DataTable();
            nextTable = dtParam.Clone();//用来记录非当前行,也就是剩余行,此方法很好,不需要重复遍历。
      for (int i = 0; i < dtParam.Rows.Count; i++)
            {
                if (dtParam.Rows[i][1].ToString() == parentid)//判断是否为当前行,如是加入currTable,否则加入nextTable

           currTable.Rows.Add(dtParam.Rows[i].ItemArray);
                }
                else
                {
                    nextTable.Rows.Add(dtParam.Rows[i].ItemArray);
                }
            }
            for (int j = 0; j < currTable.Rows.Count; j++)
            {
                DataRow dr = currTable.Rows[j];
                dr[2] = strLeftPre + dr[2].ToString();
                dtTree.Rows.Add(dr.ItemArray);//将当前行插入dtTree
      BuildTree(dtTree, nextTable, intLevel, dr[0].ToString());//处理当前行的子部门
       }

}