C#: How to get the index of the selected item(and

2019-06-01 20:16发布

问题:

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.

回答1:

ListBox.SelectedItem Property:

Gets or sets the currently selected item in the ListBox.

Or, naturally, ListBox.SelectedItems Propery:

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.



回答2:

The selected index is in the SelectedIndex property.

The selected text is in the Text property.



回答3:

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