简体   繁体   中英

See the order of multiselection in ListBox C# WinForms

Can anyone tell me how can I see the selected order of intems in a listbox in C#? For example, if I have this elements in the listbox:

Item1 Item2 Item3 Item4 Item5

and I select in this order Item4, Item2 and Item5, I need a way to find how that the items were selected in the mentioned order.

Thank you!

可能会得到所选项目的索引,并将其添加到数组中?

Expanding a little in Rudolf's idea, using a List<T> :

List<int> selected = new List<int>();

You can keep track of the items so far selected:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // add new selection:
    foreach (int index in listBox1.SelectedIndices) 
            if (!selected.Contains(index)) selected.Add(index);
    // remove unselected items:
    for (int i = selected.Count - 1; i >= 0; i-- ) 
        if (!listBox1.SelectedIndices.Contains(selected[i])) selected.Remove(i);
}

To test you can write:

for (int i = 0; i < selected.Count; i++) 
   Console.WriteLine("Item # " selected[i] + ": " + listBox1.Items[selected[i]]);

Note that when you use the expanded multiselection option you will get the usual, slightly weird Windows selection order..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM