Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last selected item in multiselect ListBox?

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.

like image 780
Germstorm Avatar asked Dec 03 '22 08:12

Germstorm


1 Answers

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);
}
like image 160
Tomalak Avatar answered Mar 27 '23 01:03

Tomalak