TreeView的子节点和父节点级联选中
参考:(TreeView的子节点和父节点级联选中)http://blog.sina.com.cn/s/blog_56616d970100c483.html
(TreeView点击文字选中和点击父节点选中子节点 )http://hi.baidu.com/lhlsxdx/blog/item/44988f8f95f006e4f01f3691.html
(C#中遍历TreeView并查找和选定节点 )http://apps.hi.baidu.com/share/detail/616013
aspx:
测试树的级联选中和取消
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
this.TreeView1.Attributes.Add("onclick", "postBackByObject()");
TreeView1.Attributes.Add("onselectednodechanged", "TreeView1_SelectedNodeChanged");
Bind();
}
}
void Bind()
{
List nodes = (List)Helper.ContactGroup().GetAllGroup(uid);
if(null == nodes)
{
return;
}
for(int i = 0; i < nodes.Count; i++)//按节点数量循环
{
TreeNode node = new TreeNode();
node.Value = nodes[i].CGID;
node.Text = nodes[i].CGName;
BindChildNode(node);
TreeView1.Nodes.Add(node);
}
}
void BindChildNode(TreeNode node)
{
List personList = (List)Helper.ContactPerson().GetContactByGID(uid, node.Value);
for(int i = 0; i < personList.Count; i++)
{
TreeNode childNode = new TreeNode();
childNode.Value = personList[i].CPID;
childNode.Text = personList[i].CPName;
node.ChildNodes.Add(childNode);
}
}
protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e) { SetChildChecked(e.Node); SetParentChecked(e.Node); }
///
///
///
程序中的对象集合大家根据自己的实际需要更改。
效果图:
选中“三级节点1”,它的的所有父节点都会选中。
C#中遍历TreeView并查找和选定节点
首先先看一段MSDN上的示例程序:打印一个树中所有节点名称
private void PrintRecursive(TreeNode treeNode)
{
// Print the node.
System.Diagnostics.Debug.WriteLine(treeNode.Text);
MessageBox.Show(treeNode.Text);
// Print each node recursively.
foreach (TreeNode tn in treeNode.Nodes)
{
PrintRecursive(tn);
}
}
// Call the procedure using the TreeView.
private void CallRecursive(TreeView treeView)
{
// Print each node recursively.
TreeNodeCollection nodes = treeView.Nodes;
foreach (TreeNode n in nodes)
{
PrintRecursive(n);
}
}
然后要说明的是一下TreeView类和TreeNode类之间的关系:TreeView类中有个只读属性是Nodes,它是属于TreeNodeCollection类型的,而对于一个TreeView它的Nodes属性就是返回treeView根结点的集合。
然后就是我的递归遍历查找一个树节点的方法(由于程序需要我是根据树节点的ImageIndex属性查找的):
private TreeNode FindTreeNode(int imageIndex, TreeNode tnParent)
{
if (tnParent == null)
return null;
if (tnParent.ImageIndex == imageIndex)
return tnParent;
TreeNode tnRet = null;
foreach (TreeNode tn in tnParent.Nodes)
{
tnRet = FindTreeNode(imageIndex, tn);
if (tnRet != null)
break;
}
return tnRet;
}
private TreeNode CallFindNode(int imageIndex, TreeView treeView)
{
TreeNodeCollection nodes = treeView.Nodes;
foreach (TreeNode n in nodes)
{
TreeNode temp = FindTreeNode(imageIndex, n);
if (temp != null)
return temp;
}
return null;
}
///
/// 这个是一个点击事件,其中改变了选中节点,
/// 改变选中节点的同时就触发了selectedNodeChanged事件
///
///
///
void myControlTransactions_AddCustomer(object sender, EventArgs e)
{
TreeNode temp = CallFindNode(3, treeView1);
if (temp != null)
treeView1.SelectedNode = temp;
}