简体   繁体   中英

How to delete node selected in ComboBox?

I want to delete child node that is selected in comboBox.

private void AccountsSetup_Load(object sender, EventArgs e)
{
    // Populating parent nodes with the items in Bank ComboBox that is First.
    string[] items = new string[BankList.Items.Count];

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

在此处输入图片说明

Despite of writing find node which is in Accounts comboBox, it does not find and obviously does not delete.

// If the Account No matches to Account node, it should delete.
TreeNode[] nodes = treeView1.Nodes.Find(AccountsComboBox2.Text, true);

foreach (TreeNode oldnode in nodes)
{
    treeView1.Nodes.Remove(oldnode);
}

My add account code, maybe i am doing something wrong here:

 treeView1.Nodes[BankList.SelectedIndex].Nodes.Add(AccountNotextBox1.Text);
        treeView1.ExpandAll();

the added account goes to AccountComboBox2.

so then I select AccountComboBox2.Text and matches if the node exist in treeview then delete it.

在此处输入图片说明

Try add Cast<TreeNode> and use Where like this.But first add Tag when you create new node.

First edit your function which add new node

   TreeNode newNode = new TreeNode(AccountNotextBox1.Text);
            //this is tag
            newNode.Tag = AccountsComboBox2.Text;
            treeView1.Nodes[BankList.SelectedIndex].Nodes.Add(newNode);

And next find node by Tag

TreeNode[] treeNodes = treeView1.Nodes
                                .Cast<TreeNode>()
                                .Where(r => r.Tag == AccountsComboBox2.Text)
                                .ToArray();

foreach (TreeNode oldnode in treeNodes)
 {
    if (oldnode.Parent == null)
    {
        treeView1.Nodes.Remove(oldnode);
    }
    else
    {
        oldnode.Parent.Nodes.Remove(oldnode);
    }
}

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