一佳一

记录像1+1一样简洁的代码

导航

树形结构 DropDownList

Posted on 2014-09-23 17:11  一佳一  阅读(1314)  评论(2编辑  收藏  举报

前台

   <asp:DropDownList ID="ddlOutType" runat="server" />

后台代码:


先绑定第一级

                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);
                }


递归查找下级

      /// <param name="Pading">空格</param>
        /// <param name="DirId">父路径ID</param>
        /// <param name="datatable">返回的datatable</param>
        /// <param name="deep">树形的深度</param>
        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);
            }
        }