当前位置: 代码迷 >> ASP.NET >> 求递归生成树的代码
  详细解决方案

求递归生成树的代码

热度:8023   发布时间:2013-02-25 00:00:00.0
求递归生成树的代码?
pid name parentid
 1 a  
 2 b 1
 3 c 2
 4 e 2
 5 f  
 6 g 5
 7 h 5
 8 w 6

要这样效果的树。。。。。。。。


------解决方案--------------------------------------------------------
//*****Build TreeView Node Code Next:

public void XT_GNML_Build_TreeNode(ref TreeView treview)
{
//****get database
DataSet DSet=(new ServerPropx.Servers()).XT_GNML_Base_Filter(""):

//***clear treeview Node
treview.Nodes.Clear();

//****create treenode object
TreeNode TRPNode=null;

//****load node
foreach(DataRow dRow in DSet.Table[0].Rows)
{
//****load Parnet dataset is zerno
if(dRow["F_Parent"].ToString()=="0")
{
TRPNode=new TreeNode():
TRPNode.Text=dRow["F_MC"].ToString();
TRPNode.ID=dRow["F_ID"].ToString():
}

//***Add TteeNode 
treview.Nodes.Add(TRPNode);

//*****filter chile Node
DataRow[] dCRow=DSet.Table[0].Select("F_PARENT='" + dRow["F_GNBH"].ToString() + "'");

XT_GNML_LoadChileTreeNode(ref dCRow,TRPNode,DSet);

}
}


private void XT_GNML_LoadChileTreeNode(ref DataRow[] dCRow,TreeNode TRCPNode,ref DataSet DSet)
{

foreach(DataRow dRow in dCRow)
{
TreeNode TREPNode=new TreeNode();
TREPNode.Text=dRow["F_MC"].ToString();
TREPNode.ID=dRow["F_ID"].ToString():

//**** Add Chile Node 
TRCPNode.Nodes.Add(TREPNode);

//*****filter chile Node
DataRow[] dPCRow=DSet.Table[0].Select("F_PARENT='" + dRow["F_GNBH"].ToString() + "'");

//***foreach load TreeNode
XT_GNML_LoadChileTreeNode(ref dPCRow,TREPNode,DSet);
}
}
------解决方案--------------------------------------------------------
C# code
// 生成树void DeptDataFill(){  DataTable dt = new SqlQuery().DtQuery("select [pid],[name],[parentid] from [table1] order by [pid]");  if (dt == null) return;  foreach (DataRow dr in dt.Rows)  {    TreeNode node = new TreeNode(dr["name"].ToString(), dr["pid"].ToString());    node.SelectAction = TreeNodeSelectAction.Select;    if (dr["parentid"] is DBNull || dr["parentid"].ToString() == "")    {      trvDept.Nodes.Add(node);    }    else    {      TreeNode node1 = FindNode(trvDept.Nodes, dr["parentid"].ToString());      if (node1 != null) node1.ChildNodes.Add(node);    }  }}// 查找节点TreeNode FindNode(TreeNodeCollection nodes, string value){  foreach (TreeNode node in nodes)  {    if (node.Value == value) return node;    TreeNode node1 = FindNode(node.ChildNodes, value);    if (node1 != null) return node1;  }  return null;}
  相关解决方案