Select index from listview

后端 未结 4 742
不思量自难忘°
不思量自难忘° 2021-01-15 03:01

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

         


        
相关标签:
4条回答
  • 2021-01-15 03:29
    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";
            }
        }
    
    0 讨论(0)
  • 2021-01-15 03:42

    Try :

    listView1.FocusedItem.Index
    

    This give you the index of the selected row.

    0 讨论(0)
  • 2021-01-15 03:46

    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...

    0 讨论(0)
  • 2021-01-15 03:49

    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.

    0 讨论(0)
提交回复
热议问题