Get single listView SelectedItem

后端 未结 9 611
闹比i
闹比i 2020-12-01 12:39

I have the MultiSelect property of the listView set to false and I\'m trying to get a single listViewItem. But the available property is SelectedItems

相关标签:
9条回答
  • 2020-12-01 13:16

    If its just a natty little app with one or two ListViews I normally just create a little helper property:

    private ListViewItem SelectedItem { get { return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null); } }
    

    If I have loads, then move it out to a helper class:

    internal static class ListViewEx
    {
        internal static ListViewItem GetSelectedItem(this ListView listView1)
        {
            return (listView1.SelectedItems.Count > 0 ? listView1.SelectedItems[0] : null);
        }
    }
    

    so:

    ListViewItem item = lstFixtures.GetSelectedItem();
    

    The ListView interface is a bit rubbish so I normally find the helper class grows quite quickly.

    0 讨论(0)
  • 2020-12-01 13:21

    I do this like that:

    if (listView1.SelectedItems.Count > 0)
    {
         var item = listView1.SelectedItems[0];
         //rest of your logic
    }
    
    0 讨论(0)
  • 2020-12-01 13:24

    Sometimes using only the line below throws me an Exception,

    String text = listView1.SelectedItems[0].Text; 
    

    so I use this code below:

    private void listView1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
        if (listView1.SelectedIndices.Count <= 0) 
        { 
            return; 
        } 
        int intselectedindex = listView1.SelectedIndices[0]; 
        if (intselectedindex >= 0) 
        {
            String text = listView1.Items[intselectedindex].Text;
    
            //do something
            //MessageBox.Show(listView1.Items[intselectedindex].Text); 
        } 
    }
    
    0 讨论(0)
提交回复
热议问题