One of the controls just about every developer seems to create is a mover.
Basically a mover consists of two list boxes, the left one containing the
available items, the one on the right containing the selected items. Selecting
one or more items and clicking a button, or drag and drop sometimes, selects or
deselects the items.
Now there are several ways of doing this but frequently people are moving
items between list box Items collection. Now this works but there is a far
easier way to handle this. Create a DataTable with the items in question. Add
two columns, the first is names Selected and of type Boolean, the second is
named Order and of type Integer.
The second is actually only needed if you want new items to appear at the bottom
of the list, leaving it out results in a fixed order of items no matter in what
order they where selected.
Now create a DataView for each of the two list boxes passing in the DataTable
in the constructor. Set the RowFilter of the available list to Selected = false
and for the selected to Selected = true. Set the Sort property to Order of
required and use these two as the DataSource for the two list boxes.
Now all you have to do is update the Selected and Order columns when the user
selects/deselects one of the items.
Public
Class Form1
Private
Sub Form1_Load(ByVal
sender As System.Object,
ByVal e As
System.EventArgs) Handles
MyBase.Load
Dim dt
As New
DataTable
dt.Columns.Add("Description",
GetType(String))
dt.Columns.Add("Selected",
GetType(Boolean))
dt.Columns.Add("Order",
GetType(Integer))
For i
As Integer
= 1 To 10
dt.Rows.Add(New
Object() {i.ToString(),
False, i})
Next
Dim dv
As DataView
dv = New
DataView(dt)
dv.RowFilter =
"Selected = false"
dv.Sort =
"Order"
lstAvailable.DataSource = dv
lstAvailable.DisplayMember =
"Description"
dv = New
DataView(dt)
dv.RowFilter =
"Selected = true"
dv.Sort =
"Order"
lstSelected.DataSource = dv
lstSelected.DisplayMember =
"Description"
End
Sub
Private
Sub cmdMoveRight_Click(ByVal
sender As System.Object,
ByVal e As
System.EventArgs) Handles
cmdMoveRight.Click
MoveSelected(lstAvailable, lstSelected)
End
Sub
Private
Sub cmdMoveLeft_Click(ByVal
sender As System.Object,
ByVal e As
System.EventArgs) Handles
cmdMoveLeft.Click
MoveSelected(lstSelected, lstAvailable)
End
Sub
Private
Sub MoveSelected(ByVal
source As ListBox,
ByVal target As
ListBox)
Dim
selected As New
List(Of DataRow)()
For
Each item As
Object In
source.SelectedItems
selected.Add(CType(item,
DataRowView).Row)
Next
For
Each row As
DataRow In selected
row("Selected")
= Not CBool(row("Selected"))
row("Order")
= Environment.TickCount
Next
End
Sub
End
Class