XTab's Blog

Ged Mead's Blog at vbCity

vbCity Blogs moved to:
http://cs.vbcity.com/blogs
  Home :: Syndication  :: Login

AprMay 2013Jun
SMTWTFS
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

Archives

Topics

Ramblings

VB.NET

  I had to revisit this problem recently and so had to recall how I did it.  Here's the scenario:  You have a ListBox and a Button.  User selects an item in the ListBox.  If they want to move that item up the list they click the button.  They can keep clicking the button until the item reaches the top of the list if they want to, or just stop when they've reached the desired position anywhere up the list.

  I don't know of any inbuilt way of doing this, so this was my fix:

1.  First set the Button's Enabled property to False in Design View (or on Form Load)

2.  When the user first selects a new item, decide if it is possible for this item to go any higher.   If it's not already at the top of the list then enable the button.

Code Copy HideScrollFull
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

    If ListBox1.SelectedIndex > 0 Then UpButton.Enabled = True

End
Sub
. . .

3.  Then make a note of the content to be moved and the element number of the next item up.

4.  Make sure that the user isn't trying to move the top item up and if they are, then avoid the Exception by exiting the sub, after first disabling the button.

5.  Temporarily store the text content in a variable.

6.  Delete (Remove) the item you are about to move. 

7.   You then reinsert the deleted text at the next element higher up the list.   

8.  Finally, you reselect and automatically highlight the item the user is moving so that the whole action appears seamless to them.

Here's the Button's code:

 

Code Copy HideScrollFull
    Private Sub UpButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpButton.Click

        ' Decide where to move item to : Note next position
        Dim NextPosition As Integer = ListBox1.SelectedIndex - 1

        ' If we have reached the top (or user selects first item manually)
        ' don't attempt the move and disable button
        If NextPosition = -1 Then
            UpButton.Enabled = False
            Exit Sub
        End If

        ' Copy the value temporarily
        Dim tempstr As String = ListBox1.SelectedItem.ToString

        ' remove the item and reinsert it one place higher
        ListBox1.Items.Remove(tempstr)
        ListBox1.Items.Insert(NextPosition, tempstr)
        ' Reselect the newly inserted item to assist the user
        ListBox1.SelectedIndex = NextPosition

    End Sub
. . .

 

   It's one of those little things that you feel should be easy, but actually needs a bit of thought to make it work.

posted on Monday, October 08, 2007 4:41 PM