Home > other >  How to select item from listview in selectedindexchanged event?
How to select item from listview in selectedindexchanged event?

Time:12-18

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
    img1 = Image.FromFile(listView1.SelectedItems[0].Text);
    pictureBox1.Image = img1;
}

I have 10 items in the listView.

If I'm using it like it is now with SelectedItems[0].Text, when I select any item, the first time it's working fine, but then when I'm selecting another item, it's throwing this error :

System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index'

CodePudding user response:

When the event is raised, the details of the item are passed into the event, via 'e'. The type of e will be a ListViewItem, therefore you can use e.Item.Text to access the text of the selected item.

The reason you may be seeing the exception is because I suspect as the selected index changes, it may be unselecting the selected item before it selects the new one, therefore, there isn't an item at Index 0 in this case. You could get around this by wrapping your existing code in an "IF" check like so:

if (listView1.SelectedItems[0] is not null) 
{
    //DO PROCESSING HERE
}

CodePudding user response:

when selected item of ListView is changed listView1_SelectedIndexChanged is called twice. You can see by using breakpoint. So you have to make this condition listView1.SelectedItems.Count > 0

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
     if (listView1.SelectedItems.Count > 0)
     {
         pictureBox1.Image = listView1.SelectedItems[0].Text;
     }
}
  • Related