Index
-
-
Dim index As Integer index = listbox1.SelectedIndex listbox1.Items.RemoveAt(index) The above code is used to remove the seleceted item from a listbox. However the program crashes when the button is clicked and no item is selected. How can I correct??
Check the value of SelectedIndex before you use it. SelectedItem will be -1 if there is nothing selected. You might also want to check to see if the number of Items in the Items collection (see it's Count property?) is greater than zero before you try to remove something from it.
A guide to posting questions on CodeProject[^]
Dave Kreskowiak Microsoft MVP Visual Developer - Visual Basic
2006, 2007 -
Dim index As Integer index = listbox1.SelectedIndex listbox1.Items.RemoveAt(index) The above code is used to remove the seleceted item from a listbox. However the program crashes when the button is clicked and no item is selected. How can I correct??
-
Dim index As Integer index = listbox1.SelectedIndex listbox1.Items.RemoveAt(index) The above code is used to remove the seleceted item from a listbox. However the program crashes when the button is clicked and no item is selected. How can I correct??
As the other posters above have stated, SelectedIndex will return -1 if there is nothing selected, so all you have to do is write an IF statement around it.
Dim index As Integer index = listbox1.SelectedIndex If index > -1 Then listbox1.Items.RemoveAt(index)
-
You asked this question yesterday and I answered it[^]. Which part of my advice did you not understand?
Paul Marfleet "No, his mind is not for rent To any God or government" Tom Sawyer - Rush