Move up button on a Listbox error

NickJ

Member
Joined
Apr 29, 2005
Messages
21
Programming Experience
Beginner
[FONT=&quot]Hi people [/FONT]

[FONT=&quot]I have a problem with this code, the code moves the selected item up until it gets to the top.[/FONT]

VB.NET:
Private Sub btnMoveUp_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles BtnMoveUp.Click
 
Dim index As Integer = LstAll.SelectedIndex
If Not LstAll.SelectedItem Is Nothing Then
LstAll.Items.Insert(index - 1, LstAll.SelectedItem)
LstAll.Items.RemoveAt(index + 1)
LstAll.SelectedIndex = index - 1
End If
End Sub
However.....
If the user accidentally presses the up button again it produces this error

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in system.windows.forms.dll

Additional information: Specified argument was out of the range of valid values.


Does anybody have any ideas..


Thanks People


Nick
 
Last edited by a moderator:
Thats great but how do you Disable the btnMoveUp in the SelectedIndexChanged event handler? (Sorry but im just starting to learn all this)

Thanks

Nick
 
SelectedIndexChanged is the default event for a ListBox so, if you don't already have a SelectedIndexChanged event handler, just double-click your ListBox and one will be generated for you. You can then just add the following code.
VB.NET:
[color=Blue]Private Sub[/color] LstAll_SelectedIndexChanged(...) [color=Blue]Handles[/color] LstAll.SelectedIndexChanged
[color=Green]     'Enable the "Move Up" button if and only if an item other than the first is selected.[/color]
[color=Blue]     Me[/color].btnMoveUp.Enabled = [color=Blue]Me[/color].LstAll.SelectedIndex > 0

[color=Green]     'Enable the "Move Down" button if and only if an item other than the last is selected.[/color]
[color=Blue]     Me[/color].btnMoveDown.Enabled = [color=Blue]Me[/color].LstAll.SelectedIndex >= 0 [color=Blue]AndAlso[/color] [color=Blue]Me[/color].LstAll.SelectedIndex < [color=Blue]Me[/color].LstAll.Items.Count - 1
[color=Blue] End Sub[/color]
 
Last edited:
Back
Top