如何获取多选ListBox中的最后一个选定项?

Ger*_*orm 2 .net listbox winforms

如何获取.Net Forms多选ListBox中的最后一个选定项?显然,如果我在列表框中选择一个项目,然后选择另一个项目,则所选项目是第一个项目.

我想获得我选择/取消选择的最后一个元素.

Tom*_*lak 7

我会采用这种一般方法:

聆听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);
}
Run Code Online (Sandbox Code Playgroud)


fle*_*esh 5

不确定我理解这个问题,但最后选择的项目将是SelectedItems数组中的最后一个,所以这样的东西应该工作:

ListItem i = list.SelectedItems[list.SelectedItems.Length-1];
Run Code Online (Sandbox Code Playgroud)


小智 5

在列表框的鼠标点击事件中使用以下代码:

private void ListBox1_MouseClick(object sender, MouseEventArgs e)
{
    string s = ListBox1.Items[ListBox1.IndexFromPoint(e.Location)].ToString();

    MessageBox.Show(s);
}
Run Code Online (Sandbox Code Playgroud)