递归绑定树形菜单
public void BindTreeVew(TreeView treeView, bool isExpanded, string selected)
{
//将获取的数据转换为 一个DataTable
DataTable dt = GetDataTable();
treeView.Nodes.Clear();//清空 树的所有节点
//筛选数组
DataRow[] rowlist = dt.Select("ParentId='0'");
if (rowlist.Length <= 0) return;
//创建跟节点
TreeNode rootNode = new TreeNode();
rootNode.Text = rowlist[0]["Text"].ToString();
rootNode.Value = rowlist[0]["NodeId"].ToString();
rootNode.Expanded = isExpanded;
rootNode.Selected = true;
//添加跟节点
treeView.Nodes.Add(rootNode);
CreateChildNode(rootNode, dt, isExpanded, seleced);
}
private void CreateChildNode(TreeNode parentNode, DataTable dt, bool isExpanded, string seleced)
{
//选择数据
DataRow[] rowList = dt.Select("ParentId=" + Convert.ToInt32(parentNode.Value));
foreach (DataRow row in rowList)
{
//创建一个新的节点了
TreeNode node = new TreeNode();
node.Text = row["Text"].ToString();
node.Value = row["NodeId"].ToString();
node.NavigateUrl=row["Url"].ToString();
node.Expanded = isExpanded;
if (node.Value == seleced)
{
node.Selected = true;
}
parentNode.ChildNodes.Add(node);
//递归调用,创建其他节点
CreateChildNode(node, dt, isExpanded, seleced);
}
}