It's holiday season, and I don't have the time/energy to ask further questions, wait for your response, copy, run, and analyze, your code, so: I'll just write a quick example of how you might implement what you describe, as I understand it now. It may not be exactly what you want, but, hopefully, you can adapt some of what you see here to your own unique case.
Let's assume: a Win Forms Project: on the Main Form, probably in some kind of ContainerControl like a Panel:
1. a TreeView: 'treeView1
2. two RadioButtons: 'rbNewParent, and 'rbUseExistingParent
3. a Button: 'btnAdd
4. a TextBox: 'textBox1
Both RadioButtons are wired-up to use the same CheckChanged EventHandler.
Behavior:
1. the user clicks on 'btnAdd
2. if the 'rbNewParent RadioButton is checked: a new Parent Node and Child Node are created, and added to the Nodes Collection of the TreeView.
3. if the 'rbUseExistingParent RadioButton is checked:
a. if there are no Nodes, or no currently selected Node, in the TreeView: a MessageBox is shown asking the user to either create a new Node, or to select a new node. Then the operation is cancelled.
b. if there is a selected Node, a new Child Node is created, and added to new Parent Node, and the Parent Node added to the Nodes Collection of the currently selected Node
using System;
using System.Windows.Forms;
namespace Dec23_CP_AddNodesExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool isNewParent;
private TreeNode currentNode;
private TreeNode newParentNode;
private TreeNode newChildNode;
private int addedNodeID = 0;
private void Form1_Load(object sender, EventArgs e)
{
treeView1.ExpandAll();
rbNewParent.Checked = true;
}
private void rbTargetSelect_CheckedChanged(object sender, EventArgs e)
{
isNewParent = rbNewParent.Checked;
}
private void btnAdd_Click(object sender, EventArgs e)
{
currentNode = treeView1.SelectedNode;
if (isNewParent)
{
newParentNode = new TreeNode(textBox1.Text + ": added Parent: " + addedNodeID.ToString());
addedNodeID++;
newChildNode = new TreeNode("added Child: " + addedNodeID.ToString());
newParentNode.Nodes.Add(newChildNode);
treeView1.Nodes.Add(newParentNode);
newChildNode.EnsureVisible();
treeView1.SelectedNode = newChildNode;
addedNodeID++;
}
else
{
if (currentNode == null)
{
if (treeView1.Nodes.Count == 0)
{
MessageBox.Show("Create a new Node, and then add Nodes to it.");
}
else
{
MessageBox.Show("Choose an existing Node to add the new Node to.");
}
return;
}
else
{
newChildNode = new TreeNode("added Child: " + addedNodeID.ToString());
currentNode.Nodes.Add(newChildNode);
newChildNode.EnsureVisible();
treeView1.SelectedNode = newChildNode;
addedNodeID++;
}
}
}
}
}