递归方法实现TreeView控件的绑定
递归方法实现TreeView控件的绑定
protected void Page_Load(object sender, EventArgs e)
{
if (this.Page.IsPostBack)
return;
TreeNode node=new TreeNode();
node.Text = "中国";
node.Value = "-1";
TreeView1.DataSource = null; // TreeView1为空
TreeView1.Nodes.Add(node);
TreeView1.CollapseAll();
bindTreeView(0, node);
}
#region 绑定数据
// 入口 条件 自调用
private void bindTreeView(int parentID,TreeNode nodes)
{
province pClass = new province();
pClass.ID = parentID.ToString();
string sql = "select *from province where code='"+pClass.ID"'";
DataSet ds = SqlFunction.returnDataSet(sql);
TreeNode node;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
node = new TreeNode();
node.Text = ds.Tables[0].Rows[i]["name"].ToString();
node.Value = ds.Tables[0].Rows[i]["id"].ToString();
nodes.ChildNodes.Add(node);
bindTreeView(Convert.ToInt32(ds.Tables[0].Rows[i]["id"]),node);
}
}
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
///导入命名空间
using System.Web.UI.WebControls;
/// <summary>
/// Summary description for TreeViewDataLevelDisplay
/// </summary>
public class TreeViewDataLevelDisplay
{
#region 声明全局变量
Softwaretailor.LMS.Model.Department model = new Softwaretailor.LMS.Model.Department();
#endregion
public TreeViewDataLevelDisplay()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// 实现树形控件的数据绑定
/// </summary>
/// <param name="treeView">树形控件</param>
/// <param name="parentId">父级编号</param>
public static void TreeViewDataBand(TreeView treeView,Guid parentId)
{
treeView.Nodes.Clear();
List<Softwaretailor.LMS.Model.Department> list = Softwaretailor.LMS.BLL.Department.GetListByParentId(parentId, " CreatedDate ASC ");
TreeNode node;
if (list != null && list.Count > 0)
{
foreach (Softwaretailor.LMS.Model.Department model in list)
{
node = new TreeNode();
node.Text = model.DepartmentName;
node.Value = model.DepartmentID.ToString();
GetTreeViewDataLevelDisplay(model.DepartmentID, node);
treeView.Nodes.Add(node);
}
}
}
/// <summary>
/// 实现树形控件级别显示数据
/// </summary>
/// <param name="parentId">父级编号</param>
/// <param name="nodes">树形节点</param>
public static void GetTreeViewDataLevelDisplay(Guid parentId, TreeNode nodes)
{
List<Softwaretailor.LMS.Model.Department> list = new List<Softwaretailor.LMS.Model.Department>();
list = Softwaretailor.LMS.BLL.Department.GetListByParentId(parentId, " CreatedDate ASC ");
if (list == null || list.Count == 0)
{
return;
}
TreeNode node;
foreach (Softwaretailor.LMS.Model.Department model in list)
{
node = new TreeNode();
node.Text = model.DepartmentName;
node.Value = model.DepartmentID.ToString();
nodes.ChildNodes.Add(node);
GetTreeViewDataLevelDisplay(model.DepartmentID, node);
}
}
}