前台
后台代码:
先绑定第一级string SQL = "SELECT CategoryID,CategoryName,ParentID FROM Category" DataTable datatable = SqlHelper.ExecuteDataTable(SQL); DataRow[] row = datatable.Select("ParentID='0'"); //添加根目录 for (int i = 0; i < row.Length; i++) { ListItem li = new ListItem(row[i]["CategoryName"].ToString(), row[i]["CategoryID"].ToString()); ddlOutType.Items.Add(li); addOtherDll("", Convert.ToInt32(row[i]["CategoryID"]), datatable, 1, ddlOutType); }
/// 空格 /// 父路径ID /// 返回的datatable /// 树形的深度 private void addOtherDll(string Pading, int DirId, DataTable datatable, int deep,DropDownList ddl) { DataRow[] rowlist = datatable.Select("ParentID='" + DirId + "'"); foreach (DataRow row in rowlist) { string strPading = ""; for (int j = 0; j < deep; j++) { strPading += " "; //用全角的空格 } //添加节点 ListItem li = new ListItem(strPading + "|--" + row["CategoryName"].ToString(),row["CategoryID"].ToString()); ddl.Items.Add(li); //递归调用addOtherDll函数,在函数中把deep加1 addOtherDll(strPading, Convert.ToInt32(row["CategoryID"]), datatable, deep + 1, ddl); } }