Patrick Patrick - 25 days ago 9
C# Question

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]);
}
}


enter image description here

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.

enter image description here

mww mww
Answer

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);
    }
}