How to get the last selected item in a .Net Forms multiselect ListBox? Apparently if I select an item in the listbox and then select another 10 the selected item is the first one.
I would like to obtain the last element that I selected/deselected.
I would take this general approach:
Listen for the SelectedIndexChanged
event and scan through the SelectedIndices
collection every time.
Keep a separate list of all selected indices, appending ones that have not been in the list, removing those that have been de-selected.
The separate list will contain the indexes in the chronological order they were selected by the user. The last element always is the most recently selected index.
// for the sake of the example, I defined a single List<int>
List<int> listBox1_selection = new List<int>();
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
TrackSelectionChange((ListBox)sender, listBox1_selection);
}
private void TrackSelectionChange(ListBox lb, List<int> selection)
{
ListBox.SelectedIndexCollection sic = lb.SelectedIndices;
foreach (int index in sic)
if (!selection.Contains(index)) selection.Add(index);
foreach (int index in new List<int>(selection))
if (!sic.Contains(index)) selection.Remove(index);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With