Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select index from listview

Tags:

c#

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)
like image 242
3D-kreativ Avatar asked Mar 04 '26 14:03

3D-kreativ


1 Answers

Because ListView doesn't contain any SelectedIndex, instead there is a property of SelectedIndices.

var indices = lvRegAnimals.SelectedIndices;
//indices[0] you can use that to access the first selected index

ListView.SelectedIndices

When the MultiSelect property is set to true, this property returns a collection containing the indexes of all items that are selected in the ListView. For a single-selection ListView, this property returns a collection containing a single element containing the index of the only selected item in the ListView.

like image 147
Habib Avatar answered Mar 07 '26 05:03

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!