使用C#可以将所有数据一次性加载到DataTable或者每次递归都从新查询表,当然效率的高低不用我说大家都知道。源码并没有使用treegrid,而是使用TB.TreeGrid 树形列表 Asp.net自定义控件 http://www.cnblogs.com/sherwinzhu/archive/2008/10/01/TreeGrid.html
1:递归查询从DB
/// <summary>
/// 递归查询数据,创建 TreeGridNode 节点
/// </summary>
/// <param name="nodes"></param>
/// <param name="bo"></param>
/// <param name="parentId"></param>
private void CreateTreeViewRecursive(TreeGridNodeCollection nodes, WorkTypeBO bo, String parentId)
{
// 查询出节点数据
IList<WorkTypeInfo> list = bo.GetWorkTypeByPid(parentId);
TreeGridNode node;
foreach (WorkTypeInfo wti in list)
{
node = new TreeGridNode("wti_id_" + wti.ID);
//将节点加到树节点中
nodes.Add(node);
// 给节点赋值
node.DataItem = wti;
// 设置第一列序号
wti.Number = ++rowIndex;
// 展开节点
node.Expand();
// 递归创建子节点
CreateTreeViewRecursive(node.ChildNodes,bo, wti.ID);
}
}
/// <summary>
/// 初始化 Tree 节点
/// </summary>
/// <param name="TreeGrid"></param>
protected void InitTreeGridManual(TreeGrid tg)
{
WorkTypeBO bo = new WorkTypeBO();
//0 表示第一级根节点菜单
CreateTreeViewRecursive(tg.Nodes, bo, "0");
tg.ManualDataBind();
}
2.递归查询从DataTable
/// <summary>
/// 递归查询数据,创建 TreeGridNode 节点
/// </summary>
/// <param name="nodes"></param>
/// <param name="bo"></param>
/// <param name="parentId"></param>
private void CreateTreeViewRecursive(TreeGridNodeCollection nodes, DataTable dataSource, String parentId)
{
string fliter = String.Format("pid={0}", parentId);
// 查询出节点数据
DataRow[] drArr = dataSource.Select(fliter);
dataSource.DefaultView.Sort = "wd_order desc";
TreeGridNode node;
foreach (DataRow dr in drArr)
{
WorkTypeInfo wti = this.getNodeObject(dr);
node = new TreeGridNode("wti_id_" + wti.ID);
//将节点加到树节点中
nodes.Add(node);
// 给节点赋值
node.DataItem = wti;
// 设置第一列序号
wti.Number = ++rowIndex;
// 展开节点
node.Expand();
// 递归创建子节点
CreateTreeViewRecursive(node.ChildNodes, dataSource, wti.ID);
// 移除已添加行,提高性能
dataSource.Rows.Remove(dr);
}
}
/// <summary>
/// 初始化 Tree 节点
/// </summary>
/// <param name="TreeGrid"></param>
protected void InitTreeGridManual(TreeGrid tg)
{
WorkTypeBO bo = new WorkTypeBO();
DataTable dt = bo.GetAllWorkTypesByDataTable();
//0 表示第一级根节点菜单
CreateTreeViewRecursive(tg.Nodes, dt, "0");
tg.ManualDataBind();
}
PS1:
public IList<WorkTypeInfo> GetWorkTypeByPid(String pid)
{
string sqlCommand = WORKDALIYSQL + " where wd_pid=@pid order by wd_order ";
DbParameter dbParam = new MySqlParameter("@pid", DbType.Int32);
dbParam.Value = pid;
IList<WorkTypeInfo> workTypes = new List<WorkTypeInfo>();
using (IDataReader dr = DBHelper.ExecuteReader(sqlCommand, dbParam)) //執行查詢,返回reader
{
WorkTypeInfo obj = null;
while (dr.Read())
{
obj = this.getDB2OBJ(dr);
workTypes.Add(obj);
}
}
return workTypes;
}
PS2:
public DataTable GetAllWorkTypesByDataTable()
{
string sqlCommand = WORKDALIYSQL;
DataSet workTypes = DBHelper.ExecuteDataSet(sqlCommand);
return workTypes.Tables[0];
}
static String WORKDALIYSQL = "select wd_id,wd_pid,wd_tagname,wd_typename,wp_typedesc,wp_worktype,wp_deptno,wp_visable,createdatetime,wd_order from da_workdailys ";