好久一段時間無上blog了, 最近在看treeview的資料, 用遞歸的方法處理sql數據庫中數據並手動加至treeview還是有點問題未太明白
Posted on 2007-05-30 10:39 马路灯 阅读(390) 评论(0) 编辑 收藏 举报以下是一段遞歸的代碼, 功能是用代碼實現treeview的實現, 不過未加入sql庫的數據實現
protected void Page_Load(object sender, EventArgs e)
{
this.TreeView1.Nodes.Clear(); //先清除treeview所有的節點
maketree(); //產生treeview
TreeView1.DataBind(); //數據綁定
}
protected void maketree()
{
TreeNode RootNode; //定義一個節點對像
for (int i = 0; i < 10;i++ ) //首先產生10個根節點
{
RootNode = new TreeNode(); //實例代一個節點對像;
RootNode.Text = "根節點" + i.ToString(); //設定節點顯示文件信息
RootNode.Value = i.ToString(); //設定節點值
this.TreeView1.Nodes.Add(RootNode); //將節點加到TreeView控件
MakeChildNode(RootNode, i); //一個遞歸函數, 產生根節點的子節點
}
}
protected void MakeChildNode(TreeNode tn, int ParentID)
{
TreeNode CHildNode;
for (int i = 0; i < ParentID; i++)
{
CHildNode = new TreeNode("子節點" + i.ToString(), i.ToString());
tn.ChildNodes.Add(CHildNode);
//MakeChildNode(CHildNode,i); //這里沒有遞歸下去, 由于只是手動實現了一下treeview的代碼, 在使用遞前需先判斷一下當節點是否有下級婁據,或控制一下遞歸的層次數量
}
}
以下是一段有問題的代碼, 無法運行成功, 問題到底在哪?鬱悶........
protected void TV_binder()
{
SqlConnection conn = DB.createConection();
SqlCommand cmd = new SqlCommand("select * from Dep",conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Dep");
cmd.CommandText = "select * from Class";
adp = new SqlDataAdapter(cmd);
adp.Fill(ds,"Class");
if (ds.Tables["Dep"].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables["Dep"].Rows.Count; i++)
{//根據sql庫插入樹節點
TreeNode tn = new TreeNode();
tn.Text = ds.Tables["Dep"].Rows[i]["DepthName"].ToString();
tn.NavigateUrl = "NavMenu.aspx?act=list&Dep=" + ds.Tables["Dep"].Rows[i]["DepID"].ToString();
this.tv_leftmenu.Nodes.Add(tn);
TV_ChildTreeNode(Convert.ToInt32(ds.Tables["Dep"].Rows[i]["DepID"].ToString()),tn,ds.Tables["Class"]);
}
}
this.tv_treeview.DataBind();
}
protected void TV_ChildTreeNode(int DepID,TreeNode tn,DataTable dt)
{
dt.DefaultView.RowFilter= "DepID";
DataView dv = dt.DefaultView;
adp.Fill(ds);
if (dv.Count > 0)
{
for (DataRowView drv in dv)
{//根據sql庫插入樹節點
TreeNode Child_tn = new TreeNode();
Child_tn.Text = drv["ClassName"].ToString();
Child_tn.NavigateUrl = "NavMenu.aspx?act=list&Dep=" + drv["DepID"].ToString();
tn.ChildNodes.Add(Child_tn);
TV_ChildTreeNode(Convert.ToInt32(drv["DepID"].ToString()), Child_tn,dt);
}
}
}