如何获取多选列表框中的最后一个选定项? [英] How to get the last selected item in multiselect ListBox?
问题描述
如何在.Net Forms multiselect ListBox中获取最后选择的项目?显然,如果我在列表框中选择一个项目,然后再选择另一个10,则所选项目是第一个.
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:
收听SelectedIndexChanged
事件,并每次浏览SelectedIndices
集合.
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);
}
这篇关于如何获取多选列表框中的最后一个选定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!