如何获取 .Net Forms 多选列表框中的最后一个选定项目?显然,如果我在列表框中选择一个项目,然后选择另外 10 个,则所选项目是第一个。
我想获得我选择/取消选择的最后一个元素。
最佳答案
我会采取这种一般方法:
听听 SelectedIndexChanged
事件并扫描 SelectedIndices
每次都收藏。
保留所有选定索引的单独列表,附加未在列表中的索引,删除已取消选择的索引。
单独的列表将包含按用户选择的时间顺序排列的索引。最后一个元素始终是最近选择的索引。
// 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);
}
关于.net - 如何获取多选列表框中的最后一个选定项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/305555/