11
2012
04

C# 组织目录树

#region 组织目录树

SqlConnection conn;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!this.IsPostBack)
{
db dbase = new db();
conn = dbase.getConn();
try
{
conn.Open();
ds = CreateDataSet();
DataTable dt = new DataTable();
dt = ds.Tables[0];
InitTree(dt, null, "0 ");

this.TreeView1.DataBind();
}
finally
{
conn.Close();
conn.Dispose();
}
}
}
//建立数据集
private DataSet CreateDataSet()
{
SqlDataAdapter sda;
DataSet ds;
string cmdselect;
cmdselect = "select * from tree ";
sda = new SqlDataAdapter(cmdselect, conn);
ds = new DataSet();
sda.Fill(ds, "tree ");
return ds;
}

//建树的基本思路是:从根节点开始递归调用显示子树
private void InitTree(DataTable dt, TreeNode node, string id)
{
DataRow[] rows = dt.Select( "ParentId= ' " + id + " ' ");//筛选出属于父节点“node”的子节点集合

foreach (DataRow drv in rows) //循环子节点集合
{
TreeNode tn = new TreeNode();
tn.Value = drv[ "NodeId "].ToString(); //存放节点ID
tn.Text = drv[ "NodeName "].ToString(); //设置节点名称
//theNode.text= " " & txt & " "
tn.ImageUrl = "image/folderopen.gif ";
if (node == null | id == "0 ")
{
this.TreeView1.Nodes.Add(tn); //添加至根节点
}
else
{
node.ChildNodes.Add(tn);//添加子节点
}
this.InitTree(dt, tn, tn.Value);//递归,添加该节点的子节点
}

}
#endregion
« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。