如何在 TreeView 和 CheckedListBox 之间来回移动项目?

How to move items back and forth between a TreeView and CheckedListBox?

我一直在尝试寻找一种方法将多个选中的项目从 TreeView 移动到 CheckedListBox。我为每一个都设置了虚拟数据,每个数据下方都有一个按钮,用于从一个容器移动到下一个容器。我从按钮开始,从 TreeView 移动到 CheckedListBox,但我遇到了麻烦。我的节点变量的对象引用未设置为对象错误的实例。这就是我正在尝试的:

代码

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each node As TreeNode In TreeView1.Nodes
        If (node.Checked) Then
            Dim name As String = node.Text.ToString
            node.Remove()
            CheckedListBox1.Items.Add(name)
        End If
    Next
End Sub

我不一定需要使用按钮来移动它们,我只需要能够一次移动多个项目。任何帮助将不胜感激,提前致谢。

您不能在 For-Each 循环中修改集合。尝试以相反的顺序循环以避免弄乱 TreeNodes 的索引顺序:

Dim movingNodes As New List(Of String)
For i As Integer = TreeView1.Nodes.Count - 1 To 0 Step -1
  Dim node As TreeNode = TreeView1.Nodes(i)
  If node.Checked Then
    movingNodes.Add(node.Text)
    node.Remove()
  End If
Next
movingNodes.Reverse()
CheckedListBox1.Items.AddRange(movingNodes.ToArray)

要将项目从 CheckedListBox 移回 TreeView:

Dim movingNodes As New List(Of String)
For i As Integer = CheckedListBox1.Items.Count - 1 To 0 Step -1
  If CheckedListBox1.GetItemChecked(i) Then
    movingNodes.Add(CheckedListBox1.Items(i))
    CheckedListBox1.Items.RemoveAt(i)
  End If
Next
movingNodes.Reverse()
For Each s As String In movingNodes
  TreeView1.Nodes.Add(s)
Next