C#:如何在 ListBox 中获取所选项目(和文本)的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/789364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:14:03  来源:igfitidea点击:

C#: How to get the index of the selected item(and the text) in ListBox

c#winformspropertieslistbox

提问by Ivan Prodanov

I have a listbox (detailed view). How do I get the index of the selected item?

我有一个列表框(详细视图)。如何获取所选项目的索引?

I also eventually want to get the text at the index, but that should be easy.

我最终也想在索引处获取文本,但这应该很容易。

采纳答案by gimel

ListBox.SelectedItemProperty:

ListBox.SelectedItem属性:

Gets or sets the currently selected item in the ListBox.

获取或设置 ListBox 中当前选定的项。

Or, naturally, ListBox.SelectedItemsPropery:

或者,自然地,ListBox.SelectedItems属性:

Gets a collection containing the currently selected items in the ListBox.

... Remarks

For a multiple-selection ListBox, this property returns a collection containing all items that are selected in the ListBox. For a single-selection ListBox, this property returns a collection containing a single element containing the only selected item in the ListBox. For more information about how to manipulate the items of the collection, see ListBox..::.SelectedObjectCollection.

The ListBox class provides a number of ways to reference selected items. Instead of using the SelectedItems property to obtain the currently selected item in a single-selection ListBox, you can use the SelectedItem property. If you want to obtain the index position of an item that is currently selected in the ListBox, instead of the item itself, use the SelectedIndex property. In addition, you can use the SelectedIndices property if you want to obtain the index positions of all selected items in a multiple-selection ListBox.

获取包含 ListBox 中当前选定项的集合。

... 评论

对于多选列表框,此属性返回一个包含在列表框中选择的所有项目的集合。对于单选 ListBox,此属性返回一个包含单个元素的集合,该元素包含 ListBox 中唯一的选定项。有关如何操作集合项的详细信息,请参阅 ListBox..::.SelectedObjectCollection。

ListBox 类提供了多种引用所选项目的方。您可以使用 SelectedItem 属性,而不是使用 SelectedItems 属性获取单选 ListBox 中的当前选定项。如果要获取当前在 ListBox 中选择的项目的索引位置,而不是项目本身,请使用 SelectedIndex 属性。此外,如果要获取多选列表框中所有选定项的索引位置,可以使用 SelectedIndices 属性。

回答by Adam Robinson

The selected index is in the SelectedIndexproperty.

所选索引位于SelectedIndex属性中。

The selected text is in the Textproperty.

选定的文本在Text属性中。

回答by CSharper

I think you mean ListView (not ListBox) so use SelectedItems and SelectedIndices properties.

我想你的意思是 ListView(不是 ListBox)所以使用 SelectedItems 和 SelectedIndices 属性。