.net - 如何获取多选列表框中的最后一个选定项目?

标签 .net winforms listbox

如何获取 .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/

相关文章:

c# - 公共(public)静态变量 c# 使用正确吗?

c# - 如何在列表列中查找相同的值并在其他行上连接字符串以获得相同的列值

c# - 如何将字典的值复制到 .Net 2.0 中的 IList 对象中?

c# - 如何使用 $ 在 DataGrid 中格式化货币?

c# - 在同一网络上将 Windows Winform 应用程序与 Android 平板电脑连接

c# - 如何设置表单可见区域的大小,减去标题和边框?

excel - 在excel中链接列表框和工作表以进行删除-VBA

c# - CollectionViewSource 初始化引发列表框的 SelectionChanged

c# - 从分隔的数据库字符串字段中选择多选列表框中的项目

c# - 使用 C#.Net 在 Windows 窗体应用程序中的弹出窗口上显示后台任务的进度