[原创]递归读取DataTable加载TreeList控件
如遇到特殊情况不能直接绑定DataSource属性加载树,此时我们只能通过编程方式加载了。下面分享一个类:
RecusiveCreateTreeList ,通过递归读取DataTable加载TreeList控件,只需写少量代码就能完成数据展示。
最重要是表结构定义,isid和ParentID组成父子结点关系。
RecusiveCreateTreeList类应用,用法很简单的:
//如转帖请注明出处,by www.csframework.com
private void btnRecusiveCreate_Click(object sender, EventArgs e)
{
//获取树数据
DataTable dt = DataProvider.Instance.GetTable("select * from [tb_department]", "tb_department");
//实例化一个加载器,用于创建树
RecusiveCreateTreeList creator = new RecusiveCreateTreeList(treeList1, dt,this.DataRow2NodeHandler);
//调用CreateTree方法
creator.CreateTree("isid", "ParentID", "0");
treeList1.ExpandAll();
}
实现DataRow转换为TreeListNode的方法。
private TreeListNode DataRow2NodeHandler(DataRow row, TreeList tree, TreeListNode parentNode)
{
TreeListNode node = tree.AppendNode(new object[]
{ row["DeptCode"], row["DeptName"], row["TagValue"] },parentNode);
return node;
}
DataRow转换为TreeListNode委托定义
public delegate TreeListNode DataRow2NodeHandler(DataRow row, TreeList tree, TreeListNode parentNode);
通用TreeList树加载器
public class RecusiveCreateTreeList
{
private TreeList _tree;
private DataTable _data;
private DataRow2NodeHandler _handle;
public RecusiveCreateTreeList(TreeList tree, DataTable data, DataRow2NodeHandler handle)
{
_data = data;
_tree = tree;
_handle = handle;
}
private DataRow[] GetRows(string parentFieldName, string parentValue)
{
string filter = string.Format("{0}={1}", parentFieldName, parentValue);
return _data.Select(filter);
}
private bool HasSubRows(string parentFieldName, string parentValue)
{
return this.GetRows(parentFieldName, parentValue).Length > 0;
}
/// <summary>
/// 生成一级菜单的树结构.
/// </summary>
public void CreateTree(string keyFieldName, string parentFieldName, string rootValue)
{
this._tree.Nodes.Clear();
this._tree.BeginUpdate();
//根结点记录
DataRow[] rows = this.GetRows(parentFieldName, rootValue);
DataRow[] childs;
string pValue;//parentValue;
string kValue;//key value
TreeListNode root;
foreach (DataRow row in rows)
{
pValue = row[parentFieldName].ToString();
kValue = row[keyFieldName].ToString();
root = _handle(row, _tree, null);
childs = this.GetRows(parentFieldName, kValue);
if (childs.Length > 0)
CreateChild(childs, root, keyFieldName, parentFieldName);
}
this._tree.EndUpdate();
}
/// <summary>
/// 生成子菜单的树结构
/// </summary>
private void CreateChild(DataRow[] childs, TreeListNode parentNode,
string keyFieldName, string parentFieldName)
{
string pValue;//parentValue;
string kValue;//key value
TreeListNode root;
foreach (DataRow row in childs)
{
pValue = row[parentFieldName].ToString();
kValue = row[keyFieldName].ToString();
root = _handle(row, _tree, parentNode);
childs = this.GetRows(parentFieldName, kValue);
if (childs.Length > 0)
CreateChild(childs, root, keyFieldName, parentFieldName);
}
}
}
Source code: