无法为填充的 TreeView 节点触发 SelectedNodeChanged 事件
Posted
技术标签:
【中文标题】无法为填充的 TreeView 节点触发 SelectedNodeChanged 事件【英文标题】:Not able to fire SelectedNodeChanged event for populated TreeView node 【发布时间】:2015-11-14 19:41:30 【问题描述】:我需要在我的代码上动态生成几个树视图,并且我希望能够按需加载节点。我有以下代码结构。我的问题是填充的 TreeView 节点的 SelectedNodeChanged 事件不会触发。运行下面的代码示例后,如果将子节点展开到多个级别,然后单击子节点,则标签将不会显示文本并且填充的节点会折叠。任何想法表示赞赏!
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;
【问题讨论】:
您能否在声明树视图的位置显示代码,如UpdateFilterTreeView
中所示,显示其完整代码。
我添加了更多代码,看看是否有帮助。
只有SelectedNodeChanged
事件没有触发或者两者都没有触发?
使用treePanel.Controls.Clear();
而不是treePanel.Dispose();
@X-TECH SelectNodeChanged 事件仅在节点被填充时才会触发
【参考方案1】:
试试下面的代码。
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 ...
【讨论】:
以上是关于无法为填充的 TreeView 节点触发 SelectedNodeChanged 事件的主要内容,如果未能解决你的问题,请参考以下文章
如何通过获取nodes.text并设置为true或false来填充Treeview node.checked为true或false