Other Why does this code fail?

Mark Read

Well-Known Member
Licensed User
Longtime User
Assuming I have a Listview, when the user selects an item, I want to delete the item from the listview.

Code:

B4X:
Sub dListView1_SelectedIndexChanged(Index As Int)
    dListView1.Items.RemoveAt(Index)
   
End Sub

This code fails but the reason was not clear at the first check. Running in debug mode shows the problem.
The user selects a value, the sub is called and the item is deleted. So far so good but deleteing the item causes a SelectedIndexChanged event where the index is now -1. The code crashes.

My solution, consume the event:

B4X:
Sub dListView1_SelectedIndexChanged(Index As Int)
    If Index=-1 Then Return
    dListView1.Items.RemoveAt(Index)
End Sub

Would seem to work but still caused problems. The better solution, store the values in a second list. Add the list to the listview as required.

B4X:
Sub dListView1_SelectedIndexChanged(Index As Int)
    If Index=-1 Then Return
    MimeList.RemoveAt(Index)
    dListView1.Items.Clear
    dListView1.Items.AddAll(MimeList)
End Sub

This works without any problems.

My question: Is this behaviour normal for a listview or is this bad programming on my behalf?
 

ilan

Expert
Licensed User
Longtime User
why are you using a different sub for that?

just call dListView1.RemoveAt(Index)

EDIT: when or were do you call the remove process?
 
Last edited:
Upvote 0

Cableguy

Expert
Licensed User
Longtime User
I had a similar issue in m'y B4X Laucher... I just encapsulated thé code in a try/catch
 
Upvote 0

ilan

Expert
Licensed User
Longtime User
sorry misunderstood your issue, try this (MouseClicked event):

B4X:
Sub dListView1_MouseClicked (EventData As MouseEvent)
    If dListView1.SelectedIndex < 0 Then Return
    dListView1.Items.RemoveAt(dListView1.SelectedIndex)
End Sub
 
Last edited:
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
I tried the MouseClicked event but the eventdata has no selectedindex????

I am in Leoben, Steiermark, 2 hours drive from Vienna.
 
Upvote 0

ilan

Expert
Licensed User
Longtime User
I tried the MouseClicked event but the eventdata has no selectedindex????

I am in Leoben, Steiermark, 2 hours drive from Vienna.

the selectedindex is part of the listview not Eventdata
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
the selectedindex is part of the listview not Eventdata

You are correct and it works just as well! Many thanks. I did not realise that the selectedindex is still visible during a mouse click.
 
Upvote 0
Top