简体   繁体   English

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

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

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. 我最终还希望将文本放在索引处,但这应该很容易。

The selected index is in the SelectedIndex property. 所选索引位于SelectedIndex属性中。

The selected text is in the Text property. 所选文本在“ Text属性中。

ListBox.SelectedItem Property: ListBox.SelectedItem属性:

Gets or sets the currently selected item in the ListBox. 获取或设置列表框中当前选择的项目。

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

Gets a collection containing the currently selected items in the ListBox. 获取一个包含ListBox中当前选定项目的集合。

... Remarks ...备注

For a multiple-selection ListBox, this property returns a collection containing all items that are selected in the ListBox. 对于多选ListBox,此属性返回一个集合,其中包含在ListBox中选择的所有项目。 For a single-selection ListBox, this property returns a collection containing a single element containing the only selected item in the ListBox. 对于单选ListBox,此属性返回一个包含单个元素的集合,该元素包含ListBox中唯一选定的项目。 For more information about how to manipulate the items of the collection, see ListBox..::.SelectedObjectCollection. 有关如何操作集合项的更多信息,请参见ListBox .. ::。SelectedObjectCollection。

The ListBox class provides a number of ways to reference selected items. ListBox类提供了多种引用所选项目的方法。 Instead of using the SelectedItems property to obtain the currently selected item in a single-selection ListBox, you can use the SelectedItem property. 可以使用SelectedItem属性,而不是使用SelectedItems属性在单选ListBox中获取当前选定的项目。 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. 如果要获取当前在列表框中选择的项目的索引位置,而不是项目本身,请使用SelectedIndex属性。 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中所有选定项的索引位置,则可以使用SelectedIndices属性。

我认为您的意思是ListView(而不是ListBox),所以请使用SelectedItems和SelectedIndices属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM