views:

1959

answers:

3

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.

+4  A: 

Not sure I understand the question, but the last selected item will be the last in the SelectedItems array, so something like this should work:

ListItem i = list.SelectedItems[list.SelectedItems.Length-1];
flesh
+4  A: 

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);
}
Tomalak
Thank you very much, you have both have been helpful
Germstorm
A: 

Try this

 private void listBox1_MouseUp(object sender, MouseEventArgs e)
    {
        int jj = listBox1.IndexFromPoint(e.X, e.Y);
        object Test = listBox1.Items[jj];
        object LatestItemSelected;
        if(listBox1.SelectedItems.Contains(Test))
            LatestItemSelected = Test;
    }

Obviously LatestItemSelected is redundant and is there to emphasize that you have found your item.

Khadaji