Get the index of Item selected in ListView
If you are using the .NET Compact Framework, SelectedIndex
is not supported. For a general solution, I prefer SelectedIndices
:
ListView.SelectedIndexCollection indices = lst.SelectedIndices;
if (indices.Count > 0)
{
// Do something with indices[0]
}
For Visual Studio 2015, SelectedIndex
does not seem to be available. Instead, you can use SelectedIndices[x]
where x=0
will give you the first selected item:
listView.SelectedIndices[0]
You can also set the MultipleSelect
property to false
to only allow one item to be selected at a time.
You can get SelectedIndex
from listView. No need to traverse over all items because as per your code you seems to be interested in index of any selected item.
var2 = ListView1.SelectedIndex;
OR
simply this will work if interested in only first index:
if (lst.SelectedItems.Count > 0)
{
var2 = lst.Items.IndexOf(lst.SelectedItems[0]);
}