树控件,父子ID 无限级菜单

SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
protected void addTree(int ParentID, TreeNode pNode)
{
//打开数据库 
sqlconn.Open();

//把数据添加到数据表中 
SqlDataAdapter da = new SqlDataAdapter("select * from Departments", sqlconn);
sqlconn.Close();
DataSet dataSet = new DataSet();
da.Fill(dataSet, "order");
DataTable dataTable = dataSet.Tables["order"];
DataView dvTree = new DataView(dataTable);

//过滤数据,选择当前父结点下的所有子结点 
dvTree.RowFilter = "[ParentId] = " + ParentID;


//循环当前所有子结点 
foreach (DataRowView Row in dvTree)
{
TreeNode node = new TreeNode();


//如果当前结点为根结点 
if (pNode == null)
{
//显示结点的文字信息并加入TreeView2中 
node.Text = Row["DeptName"].ToString();
node.Value = Row["DeptId"].ToString();
//添加为根结点 
treeview2.Nodes.Add(node);

//递归调用,把当前结点作为根结点继续添加所有子结点 
addTree(Int32.Parse(Row["DeptId"].ToString()), node);
}


//如果当前结点为子结点 
else
{
//显示结点的文字信息并加入链接地址 
node.Text = Row["DeptName"].ToString();
node.Value = Row["DeptId"].ToString();
//添加为子结点 
pNode.ChildNodes.Add(node);

//递归调用,把当前结点作为根结点继续添加所有子结点 
addTree(Int32.Parse(Row["DeptId"].ToString()), node);
}
}
}

protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
Session["page"] = Request.QueryString["page"];
treeview2.Nodes.Clear();
//调用添加结点函数(根结点的父结点ID为0) 
addTree(0, (TreeNode)null);
treeview2.ExpandDepth = 0;
}
}

你可能感兴趣的:(id)