无法为已填充的TreeView节点触发SelectedNodeChanged事件

时间:2015-08-21 00:23:17

标签: c# asp.net treeview

我需要在我的代码上动态生成几个treeview,并希望能够按需加载节点。我有以下代码结构。我的问题是SelectedNodeChanged事件,因为填充的TreeView节点不会触发。在代码示例下面运行后,如果将子节点扩展到多个级别,然后单击子节点,则标签将不显示文本,并且填充的节点将折叠。任何想法都表示赞赏!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TreeViewTest : System.Web.UI.Page
{
    private const int Count = 2;
    private string[] codeList = { "th", "os" };

    protected void Page_Load(object sender, EventArgs e)
    {
        updateTree();
    }


    protected void updateTree()
    {

        treePanel.Controls.Clear();
        TreeView[] treeList = new TreeView[Count];

        for (int i = 0; i < Count; i++)
        {
            var tree = new TreeView();
            tree.ID = "treelist" + i.ToString();

            tree.TreeNodePopulate += TreeBranch_SelectedNodePopulate;
            tree.SelectedNodeChanged += TreeBranch_SelectedNodeChanged;
            string codeName = codeList[i];
            TreeNode codeNode = new TreeNode(codeName, codeName);
            codeNode.SelectAction = TreeNodeSelectAction.Select;
            codeNode.PopulateOnDemand = true;
            tree.Nodes.Add(codeNode);
            tree.ExpandDepth = 2;
            treePanel.Controls.Add(tree);
            treeList[i] = tree;
        }
    }

    protected void TreeBranch_SelectedNodeChanged(object sender, EventArgs e)
    {
        TreeView treeview = (TreeView)sender;
        string text = treeview.SelectedNode.Text;
        Label1.Text = text;
    }


    protected void TreeBranch_SelectedNodePopulate(object sender, TreeNodeEventArgs e)
    {
        LoadChildNode(e.Node);
    }


    public void LoadChildNode(TreeNode parentNode)
    {
        TreeNode childNode = new TreeNode("childNode","childNode");
        parentNode.ChildNodes.Add(childNode);
        childNode.PopulateOnDemand = true;
    }

}

1 个答案:

答案 0 :(得分:0)

请尝试以下代码。

treePanel.Controls.Clear();
TreeView[] treeList = new TreeView[codebaseCount]; //But I recommend you use List<TreeView> instead of TreeView[];
for (int i = 0; i < codebaseCount; i++)
{
    var tree = new TreeView();
    tree.ID = "treelist" + i.ToString();
    tree.TreeNodePopulate += TreeBranch_SelectedNodePopulate;
    tree.SelectedNodeChanged += TreeBranch_SelectedNodeChanged;
    TreeNode newNode = new TreeNode(newName,newName);
    newNode.SelectAction = TreeNodeSelectAction.None;
    newNode.Expand();
    tree.Nodes.Add(newNode);
    tree.ExpandDepth = 2;
    treePanel.Controls.Add(tree);
    treeList[i] = tree;        
    // more code ...
}