最近的项目里需要为DropDownList绑定一个树形的数据源!因为是第一次绑定树形数据结构。再加上当时么有网络只能自己写算法!现在把算法和绑定时需要注意的地方贴上来。为以后的同学提个醒!
先是算法的设计,其实现在网上有很多现成的算法。但是当时我没有联网只能自己设计算法了。我用的数据库结构类似下面的表
字段名称 | 字段类型 | 是否为空 | 字段说明 |
ID | int | No | 主键ID |
ParentID | int | No | 父级ID |
Name | Nvarchar | No | 显示的名称 |
其中父级ID为0的是顶级栏目。
新建一个DataTble用来作为DropDownLst的数据源。
先将最顶级的栏目保存到DataTable中,然后循环DataTable中的每一项。如果该项存在子栏目就递归调用。如果不存在子栏目就进行下一次循环。
代码如下:
private void TreeDataBind() { #region 新建一个DataTable用来作为DropDownList的数据源 DataTable table = new DataTable(); table.Columns.Add("ID"); table.Columns.Add("Name"); #endregion using (SqlConnection Connection = new SqlConnection(strSqlConnstring)) { #region 先将顶级的菜单放入table表中 SqlCommand Command = Connection.CreateCommand(); Command.CommandText = "SELECT ID,Name FROM Test WHERE Parent=0"; Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(Command); DataSet ds = new DataSet(); da.Fill(ds); if (ds != null && ds.Tables[0].Rows.Count > 0) { foreach (DataRow dr in ds.Tables[0].Rows) { table.Rows.Add(dr["ID"].ToString(), dr["Name"].ToString()); Recursive(Convert.ToInt32(dr["ID"]), ref table); } } #endregion } #region 绑定数据源 this.dropList.DataSource = table; this.dropList.DataValueField = "ID"; this.dropList.DataTextField = "Name"; this.dropList.DataBind(); #endregion } /// <summary> /// 用于递归的方法 /// </summary> /// <param name="ID">需要查询的栏目的ID</param> /// <param name="table">用于存放数据的Table</param> private void Recursive(int ID, ref DataTable table) { string strSql = string.Format("SELECT ID,Name FROM Test WHERE Parent={0}", ID); using (SqlConnection Connection = new SqlConnection(strSqlConnstring)) { SqlCommand Command = Connection.CreateCommand(); Command.CommandText = strSql; Connection.Open(); SqlDataAdapter da = new SqlDataAdapter(Command); DataSet ds = new DataSet(); da.Fill(ds); //如果DataSet不为空,就说明表中有以ID作为Parent的记录 if (ds != null && ds.Tables[0].Rows.Count > 0) { sbDepth.Append(" ");//这里的空格一定要用全角的空格!否在在页面显示的时候显示不出效果 foreach (DataRow dr in ds.Tables[0].Rows) { //将DataRow插入到现有的DataTable表中。 table.Rows.Add(dr["ID"].ToString(), sbDepth.ToString() + dr["Name"].ToString()); //递归调用Resursive方法,来查询是否有以新的ID作为Parent的记录 Recursive(Convert.ToInt32(dr["ID"]), ref table); } //循环结束时不要忘记减少缩进行的空格数量。 string strSb = sbDepth.ToString(); if (strSb.Contains(" ") && strSb.Length >= 1) { sbDepth.Remove(strSb.Length - 1, 1); } } } }
现在在数据库中插入如下图所示的数据
然后运行项目得到最终的显示结果