このページをはてなブックマークに追加このページを含むはてなブックマーク このページをlivedoor クリップに追加このページを含むlivedoor クリップ

目次

2つのリストボックス間でアイテムを移動する

 ListBox1,ListBox2という2つのリストボックスをフォームに貼り付け、Button1をクリックすることでListBox1で選択したアイテムがListBox2に移動する(移動元のListBox1からはアイテムが消える)。また、Button2をクリックすることでListBox2で選択したアイテムがListBox1に移動する。

方法1

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
Public Class Form1
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With ListBox1
            .SelectionMode = SelectionMode.MultiExtended
        End With
        With ListBox2
            .SelectionMode = SelectionMode.MultiExtended
        End With
 
        'アイテムを追加する。
        ListBox1.Items.AddRange(New String() {"池袋駅", "上野駅", "秋葉原駅", "東京駅", "品川駅", "渋谷駅", "新宿駅"})
    End Sub
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        moveItem(ListBox1, ListBox2)
    End Sub
 
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        moveItem(ListBox2, ListBox1)
    End Sub
 
    Private Sub moveItem(ByVal lstFrom As ListBox, ByVal lstTo As ListBox)
        Dim currentIndex As Integer
        For i = 0 To lstFrom.SelectedIndices.Count - 1
            currentIndex = lstFrom.SelectedIndices(0)
            lstTo.Items.Add(lstFrom.Items(currentIndex))
            lstFrom.Items.RemoveAt(currentIndex)
        Next
    End Sub
 
End Class

方法2

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
Public Class Form2
 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With ListBox1
            .SelectionMode = SelectionMode.MultiExtended
        End With
        With ListBox2
            .SelectionMode = SelectionMode.MultiExtended
        End With
 
        'アイテムを追加する。
        ListBox1.Items.AddRange(New String() {"池袋駅", "上野駅", "秋葉原駅", "東京駅", "品川駅", "渋谷駅", "新宿駅"})
    End Sub
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        moveItem(ListBox1, ListBox2)
    End Sub
 
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        moveItem(ListBox2, ListBox1)
    End Sub
 
    Private Sub moveItem(ByVal lstFrom As ListBox, ByVal lstTo As ListBox)
        For i = 0 To lstFrom.SelectedItems.Count - 1
            lstTo.Items.Add(lstFrom.SelectedItems(i))
        Next
        For i = lstTo.SelectedIndices.Count - 1 To 0 Step -1
            lstFrom.Items.RemoveAt(lstTo.SelectedIndices(i))
        Next
    End Sub
 
End Class