简体   繁体   中英

How to add/remove child nodes from textbox to the selected node in combobox

在此处输入图片说明

  • I'm adding items from combobox to treeview at run-time.

The code goes as follows:

 private void Form1_Load(object sender, EventArgs e)
    {
        comboBox1.SelectedIndex = 0;

        string[] items = new string[comboBox1.Items.Count];

        for (int i = 0; i < comboBox1.Items.Count; i++)
        {
            items[i] = comboBox1.Items[i].ToString();
            treeView1.Nodes.Add(items[i]);
        }
    }

Now I want to add child node to the selected node in combobox.

在此处输入图片说明

When I add child for root node - 2 it goes at the bottom, as displayed in the picture above.

 private void AddChildNodeButton_Click(object sender, EventArgs e)
    {
        treeView1.Nodes.Add(comboBox1.Text, textBox1.Text);
    }

To add to a selected note, use the SelectedNode method, and instead of using the combox1 dropdown, you can just select the node in the tree, like below:

private void AddChildNodeButton_Click(object sender, EventArgs e)
{

    treeView1.SelectedNode.Nodes.Add(textBox1.Text)
}

If you want to use the combobox, it will be a little slower since you first have to search the treeview using that text

       TreeNode[] tns=treeView1.Nodes.Find(comboBox1.Text, true);
        if (tns.Length > 0)
        {

            treeView1.SelectedNode = tns[0];
            treeView1.SelectedNode.Nodes.Add(textBox1.Text)
        }

Found the answer myself, this works for me.

treeView1.Nodes[comboBox1.SelectedIndex].Nodes.Add(textBox1.Text);

to next question, keeping the data save.

I want to add selected item in combobox to treeview and remove selected item in combobox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM