首先需要一个关系数据库表结构:就这个结构
NodeId | ModualID | NodeName | NodeURL |
1 | <null> | head1 | URL |
2 | <null> | head2 | URL |
3 | <null> | head3 | URL |
4 | 1 | head11 | URL |
5 | 2 | head21 | URL |
6 | 3 | head31 | URL |
public void inimenu(string strrole)
{
InitTree(this.TreeView_Menu, Appclass.TreeDataSet(strrole));
}
//这里Appclass.TreeDataSet(strrole)为通过用户角色strrole来初始绑定treeview对应DataSet
public static DataSet TreeDataSet(string Role)
{
}
public bool InitTree(TreeView treeview, DataSet ds)
{
treeview.Nodes.Clear();
ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["NodeId"], ds.Tables[0].Columns["ModualID"], false);
foreach (DataRow dbRow in ds.Tables[0].Rows)
{
if (dbRow.IsNull("ModualID"))
{
TreeNode newNode = CreateNode(dbRow["NodeName"].ToString(), dbRow["NodeId"].ToString(), dbRow["NodeURL"].ToString());
treeview.Nodes.Add(newNode);
SubTree(dbRow, newNode);
}
}
treeview.ExpandAll();
return true;
}
private void SubTree(DataRow dbRow, TreeNode node)
{
foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
{
TreeNode childNode = CreateNode(childRow["NodeName"].ToString(), childRow["NodeId"].ToString(), childRow["NodeURL"].ToString());
node.ChildNodes.Add(childNode);
SubTree(childRow, childNode);
}
}
private TreeNode CreateNode(string text, string tag,string url)
{
TreeNode node = new TreeNode();
node.Text = text;
node.Value = tag;
node.NavigateUrl = url;
return node;
}
{
InitTree(this.TreeView_Menu, Appclass.TreeDataSet(strrole));
}
//这里Appclass.TreeDataSet(strrole)为通过用户角色strrole来初始绑定treeview对应DataSet
public static DataSet TreeDataSet(string Role)
{
}
public bool InitTree(TreeView treeview, DataSet ds)
{
treeview.Nodes.Clear();
ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["NodeId"], ds.Tables[0].Columns["ModualID"], false);
foreach (DataRow dbRow in ds.Tables[0].Rows)
{
if (dbRow.IsNull("ModualID"))
{
TreeNode newNode = CreateNode(dbRow["NodeName"].ToString(), dbRow["NodeId"].ToString(), dbRow["NodeURL"].ToString());
treeview.Nodes.Add(newNode);
SubTree(dbRow, newNode);
}
}
treeview.ExpandAll();
return true;
}
private void SubTree(DataRow dbRow, TreeNode node)
{
foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
{
TreeNode childNode = CreateNode(childRow["NodeName"].ToString(), childRow["NodeId"].ToString(), childRow["NodeURL"].ToString());
node.ChildNodes.Add(childNode);
SubTree(childRow, childNode);
}
}
private TreeNode CreateNode(string text, string tag,string url)
{
TreeNode node = new TreeNode();
node.Text = text;
node.Value = tag;
node.NavigateUrl = url;
return node;
}
run ------>
可以了,呵呵