2016-11-14 57 views
0

我想要刪除在comboBox中選擇的子節點。如何刪除在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

儘管這是在賬戶組合框寫作查找節點,它沒有找到,顯然不會刪除。

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

我的附加科目代碼,也許是我在這裏做得不對:

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

添加的帳戶去AccountComboBox2。

所以然後我選擇AccountComboBox2.Text並匹配如果節點存在於treeview然後刪除它。

enter image description here

+0

添加新節點

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

並查找下一個節點,我不看到你試圖找到所選項目。另外,當您迭代它時,您無法從集合中刪除項目。 – krillgar

+0

當我按下「刪除帳戶」按鈕,它遍歷treeView1.nodes,並找到帳戶號碼「123123123是否存在,如果存在,它應該刪除該節點。 – Patrick

+0

我不能刪除項目,而迭代它?那麼我有選擇要刪除的節點?如果我不想讓用戶選擇要刪除的節點,因爲當創建帳戶時它會進入comboBox,並且當用戶選擇要刪除的comboBox帳戶時,所有東西都可以正常工作。用戶可以知道他們在哪裏銀行帳戶 – Patrick

回答

1

嘗試添加Cast<TreeNode>和使用Where就像當你創建新的節點this.But第一添加標籤。

首先編輯你的功能,通過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); 
    } 
} 
+0

對不起,這不起作用,這看起來非常好的代碼壽。 – Patrick

+0

@Patrick嘗試檢查你嘗試刪除有父母的節點或沒有,因爲我顯示。 –

+0

好吧,我正在嘗試這段代碼。 – Patrick