Daniel Halfoni
Daniel Halfoni

Reputation: 507

How can I get a listview item index when clicking on the item?

For example if I click on the first item it will be at index 0. If I click on item 15 then the index should be 16.

I tried

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = listView1
        }

But I'm not sure if this is the right event or I should use the listView1_Click event ?

And the listView1 does not have any property SelectedIndex. And last thing is I want to get the item text according to the index of the item I clicked on.

Upvotes: 1

Views: 9049

Answers (5)

user7728262
user7728262

Reputation: 1

First you can get listview item object like below

ListViewItem lst=(ListViewItem)listView.SelectedItems[0];

from that object(lst) you can get the text like below

string text=lst.Content.ToString();

Upvotes: 0

Stoyan Bonchev
Stoyan Bonchev

Reputation: 537

According to MSDN, there is still SelectedIndex. In my opinion your event is wrong, but you can still see it by .SelectedIndex. As it was mentioned before. UPDATE: according to the comment, the link is fixed for the correct case.

Upvotes: -1

Stanley S
Stanley S

Reputation: 1052

Assuming you want the index of the currently selected item you can do it like this :
int index = ListView1.FocusedItem.Index

Upvotes: 3

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Use ListView.SelectedIndices property:

List<int> selectedIndices = listView1.SelectedIndices.Cast<int>().ToList();

It returns collection of selected indices (because by default you can select several items in listview if you click on items with Ctrl or Shift key pressed). Also note that when you deselect all items, this collection will be empty and things like listView1.SelectedIndices[0] will throw IndexOutOfRange exception.

But if you will set MultiSelect property to false. Then this collection will always contain zero or one item. You can use Count property of SelectedIndicesCollection to check if item was selected:

 if (listView1.SelectedIndices.Count > 0)
 {
    int selectedIndex = listView1.SelectedIndices[0];
 }

Upvotes: 3

James
James

Reputation: 2911

You need to use the selected indices list you can also do this be item too.

listView1.SelectedIndices[0]

Upvotes: 0

Related Questions