Paul Chilton electronics, programming, server administration

16Apr/110

VB.NET Move ListViewItems Up and Down

ListView

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 ListViewByVal 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

 

Posted by Paul

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.