Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
970 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...