Search code examples
asp.netvb.netlistboxselectedindex

VB.NET List Box Selected Index


I seem to be having issues with the selected index on a list box.

The list box is having various items inserted depending on the user selection. An example would be:

LiIndex = ListBox1.Items.Count      
ListBox1.Items.Insert(LiIndex, "Item1")

LiIndex = ListBox1.Items.Count      
ListBox1.Items.Insert(LiIndex, "AND")

LiIndex = ListBox1.Items.Count      
ListBox1.Items.Insert(LiIndex, "Item2")

LiIndex = ListBox1.Items.Count      
ListBox1.Items.Insert(LiIndex, "AND")

LiIndex = ListBox1.Items.Count      
ListBox1.Items.Insert(LiIndex, "Item3")

This all work and displays without a problem. The issue I have is if I select the second of the two AND's. If I click the second "AND" in the list and then a button to fire a method, the selected index is always the index of the first "AND".

Dim listIndex as integer = ListBox1.SelectedIndex

I can't work out why, the listbox itself will always show the second one as selected, but the action will happen against the first one.

Any ideas as to where I am going wrong would be greatly appreciated.


Solution

  • Wathever you want to achieve, handling the ListBox items directly is not a good place to start. You should use an ObservableList(Of String) as a property of your code and bind the list in xaml.
    After that your code becomes : MyItemList.Add("My Item")
    The issue might come from using SelectedItem in your code OR from the fact your're displaying same object twice (i once had a strange behaviour in a CheckBox displaying twice same object) you can get rid of that by defining/using a class to store the data : anyway, it is not just about a string, no ? so you can have an ItemInfo class with a ToString Overload for it to display OR you define a DataTemplate in your Window resource that has ItemInfo as DataType.

    <DataTemplate DataType="{x:Type l:ItemInfo}">
            <TextBlock Text="{Binding ItemText}" />
    </DataTemplate>  
    

    and in your code you use, MyItemList beeing now an ObervableList(Of ItemInfo) : MyList.Add(New ItemInfo(" some text", ...) )
    so you never have twice same item.

    More work, but here we have more solid start to add data/functions after.