I always use this code to retrieve selected row from a listbox
dim row as Integer = Listbox1.ListIndex
If row < 0 Or row >= Listbox1.ListCount Then
// Do Something
I know that Listbox1.ListIndex = -1 happen when there is no selected row. But, Is there any chances of Listbox1.ListIndex value will be higher or equal than Listbox1.ListCount?
No, but that doesn’t make the test any less valid. Defensive coding and all that.
I do not think so.
I can tell you that the number of lines in a listbox (listcount) is base 1
Listindex is base 0 and never is equal listcount :
if listbox1.listindex > -1 then
// do Something
I use Listbox1.SelCount > 0 instead.
It basically does the same thing as Listbox1.ListIndex > -1. It just offers me more flexibility. It kinda became my personal preference.
The SelCount value will be 1 of some row is selected. But obviously higher than 1 in case multiple rows are selected. In many cases, I have to display other types of data when multiple rows are selected.
And no, the ListIndex value will never be higher than the index number of the last row: ListCount - 1. (Minus one, because ListCount is 1 based, as Massimiliano mentioned)
Thank you all. That’s make me feel safe to remove
Or row >= Listbox1.ListCount
The only place you might be able to find the value of row >= ListCount is in the CellBackgroundPaint event of a listbox. Since all cells will fire this event, there is a change that the row value of that event might be higher than ListCount-1