Moving items up or down in a listbox
So I really didn't think this was that complicated to do. Changing the order of items that are displayed in a standard list box. Nothing all that fancy. It being a Monday, I decided to try and not think and just to grab some code from somewhere on the internet.I was surprised by the wide variety of different ways to do this and all of them seemed overly complicated. One involving a nested for loop or another messing with the data source and saying that it only worked when the box was bound. Craziness.
All of this seemed way to complicated. So I broke down and thought about it for a second, and came up with (I think) the easiest way to move an item up or down in a list box control in .Net.
'down button press
Private Sub btnDown_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDown.Click
Dim index As Integer = Me.lbxSortOrder.SelectedIndex
Dim itemCount As Integer = Me.lbxSortOrder.Items.Count
Dim li As ListItem = Me.lbxSortOrder.Items(index)
Dim newIndex As Integer
If index = itemCount - 1 Then
newIndex = index
Else
newIndex = index + 1
End If
Me.lbxSortOrder.ClearSelection()
Me.lbxSortOrder.Items.Remove(li)
Me.lbxSortOrder.Items.Insert(newIndex, li)
li.Selected = True
End Sub
The up button press is the same exact thing except the text on the index needs to look like this:
If index = 0 Then
newIndex = 0
Else
newIndex = index - 1
End If
And thats it. I know it was simple, I thought about not posting this cause of its simplicity, but by looking what else was out there, I'll add my two cents.
Labels: .NET
posted by Tom Becker at
2/11/2008
![]()

1 Comments:
Thanks for the code. I don't know why I didn't think of this simple solution on my own.
September 26, 2008 7:06 PM
Post a Comment
<< Home