Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of Item selected in ListView

I've been searching for about an hour already and couldn't find a best solution. I am migrating from VB.NET to C# Forms and to C# WPF. Never mind that... so I use this code for C# forms and it works, but not in C# WPF

 if (ListView1.SelectedItems.Count > 0)
            {
                for (lcount = 0; lcount <= ListView1.Items.Count - 1; lcount++)
                {
                    if (ListView1.Items[lcount].Selected == true)
                    {
                        var2 = lcount;
                        break;
                    }
                }
            }

this is the way I want to get the index of the item clicked in listbox. I have the error in .SELECTED

please help.

like image 448
Glenn Posadas Avatar asked Jan 24 '14 08:01

Glenn Posadas


2 Answers

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.

like image 164
Luis Conejo-Alpizar Avatar answered Sep 27 '22 19:09

Luis Conejo-Alpizar


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]);
}
like image 33
Rohit Vats Avatar answered Sep 27 '22 19:09

Rohit Vats