Reputation: 8646
I have a treeview with a root node initially as Root. If i right click on Root node i will have a context menu displayed with some options as New and other if i select New i will add a child node to the Root node. If i again Right click on the Root node and if the Root has child nodes i would like to clear all child nodes and add a new child node how can i do this
Upvotes: 5
Views: 27769
Reputation: 503
You can also try the opposite, i.e. check if current node has a parent.
if(treeView1.SelectedNode.Parent == null) {} //parent
else{} //child
Upvotes: 0
Reputation: 1
foreach (TreeNode node in treeview.Nodes)
{
if (node.ChildNodes.Count != 0)
{
//Node exists
}
else
{
//Node doesn't exists
}
}
Upvotes: -1
Reputation: 371
In the 'right click'
handler, assuming you use Mouse Click, you can use the event args TreeNodeMouseClickEventArgs to get the current node ...
void tv_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
TreeNode selectedNode = e.Node;
}
}
Upvotes: 0
Reputation: 8646
After all the final answer is as follows
if (tvwACH.HitTest(location).Node.Nodes.Count > 0 && tvwACH.SelectedNode.Parent == null )
{
foreach (TreeNode node in tvwACH.Nodes)
{
node.Nodes.Clear();
}
}
Upvotes: 1
Reputation: 767
You can check TreeNode.Nodes property. If count is greater than zero then you have child nodes, otherwise not
Upvotes: 0
Reputation: 55059
TreeNode.Nodes gives you a list of all child nodes to the node you're looking at.
You can then call Clear on that collection to delete all childnodes.
Upvotes: 6