VB.NET Move ListViewItems Up and Down
I recently wrote an application where I needed to move items up and down (order them) in ListView in VB.NET and discovered that there isn't a built in method to do so. I decided to share my solution which is shown below. This method can be used to move one or multiple selected items up or down in the list. All tag information and formatting should 'follow' the items moved. This method is easily ported to C#.
''' <summary>
''' Move selected items up or down in the specified listview
''' </summary>
''' <param name="lvwListView">The listview to manipulate</param>
''' <param name="blnMoveUp">True to move items up, False to move them down</param>
Private Sub MoveItemsInListView(ByRef lvwListView As ListView, ByVal blnMoveUp As Boolean)
Try
'Set the listview index to limit to depending on whether we are moving things up or down in the list
Dim intLimittedIndex As Integer = (lvwListView.Items.Count - 1)
If blnMoveUp Then intLimittedIndex = 0
'Define a new collection of the listview indexes to move
Dim colIndexesToMove As New List(Of Integer)()
'Loop through each selected item in the listview (multiple select support)
For Each lviSelectedItem As ListViewItem In lvwListView.SelectedItems
'Add the item's index to the collection
colIndexesToMove.Add(lviSelectedItem.Index)
'If this item is at the limit we defined
If lviSelectedItem.Index = intLimittedIndex Then
'Do not attempt to move item(s) as we are at the top or bottom of the list
Exit Try
End If
Next
'If we are moving items down
If Not blnMoveUp Then
'Reverse the index list so that we move items from the bottom of the selection first
colIndexesToMove.Reverse()
End If
'Loop through each index we want to move
For Each intIndex As Integer In colIndexesToMove
'Define a new listviewitem
Dim lviNewItem As ListViewItem = CType(lvwListView.Items(intIndex).Clone(), ListViewItem)
'Remove the currently selected item from the list
lvwListView.Items(intIndex).Remove()
'Insert the new item in it's new place
If blnMoveUp Then
lvwListView.Items.Insert(intIndex - 1, lviNewItem)
Else
lvwListView.Items.Insert(intIndex + 1, lviNewItem)
End If
'Set the new item to be selected
lviNewItem.Selected = True
Next
Catch ex As Exception
Trace.WriteLine("MoveItemsInListView() has thrown an exception: " & ex.Message)
Finally
'Set the focus on the listview
lvwListView.Focus()
End Try
End Sub
Enjoy this article?
Posted by Paul
Recent Posts
- VPN Setup With LT2P & IPSEC
- Unipolar Stepper Motor Driver
- Electronics Testing
- Apache & PHP Setup in Windows
- VB.NET Move ListViewItems Up and Down
- Advent VEGA Tablet PC
- CrashPlan Online Backup on QNAP TS-210 NAS
- Dropbox
- Delete all Picasa Web Albums
- Converting CVSNT to Linux CVS
Tags
Archive
- November 2011 (4)
- April 2011 (1)
- March 2011 (1)
- January 2011 (1)
- December 2010 (1)
- September 2010 (1)
- May 2010 (1)
- April 2010 (8)
- March 2010 (1)
- March 2009 (1)




