'Select index from listview

I'm having some problem to get the index of the selected row in a listview. I wonder why this code isn't working? I get a red line below the SelectedIndex

    private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = lvRegAnimals.SelectedIndex;
        string specialData = motelManager.GetInfoFromList(index);
        UppdateSpecialData(specialData);
    }

Help is preciated. Thanks!

EDIT:

For some strange reason I get two messages when I click on one of the lines in the listView!? First I get the previous number and then the number for the last clicked line. What could be wrong?

 private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
    {
        int index = lvRegAnimals.FocusedItem.Index;
        MessageBox.Show(Convert.ToString(index));
    }

It's working now when I added a check like this:

if(lvRegAnimals.SelectedIndices.Count > 0)


Solution 1:[1]

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Acquire SelectedItems reference.
        var selectedItems = listView1.SelectedItems;
        if (selectedItems.Count > 0)
        {
        // Display text of first item selected.
        this.Text = selectedItems[0].Text;
        }
        else
        {
        // Display default string.
        this.Text = "Empty";
        }
    }

Solution 2:[2]

Try :

listView1.FocusedItem.Index

This give you the index of the selected row.

Solution 3:[3]

There is another thread like this one, but here it goes again.

It can return NULL. Also the SelectedIndexChanged event can be FIRED TWICE. And the first time, there nothing selected yet.

So the only safe way to find it is like this:

    private void lv1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lv1.FocusedItem == null) return;
        int p = lv1.FocusedItem.Index;

... now int p has the correct value...

Solution 4:[4]

The ListView is a darn hassle to work with sometimes. A simple solution i've used is a for loop that checks for the selected Item.

I've put my solution in the "When index change trigger" within the ListView. Example:

int sel_item = 0; //an int to store the selected item index.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
      for (int i = 0; i < listView1.Items.Count; i++)
      {
             if (listView1.Items[i].Selected == true)
             {
              sel_item = i;
             }
      }
}

This would ofcourse only work correctly with the "Multiselection" option set as false.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Roger Deep
Solution 4 GravityBug