简体   繁体   中英

Double-Clicking Item in ListView

So I added a list view, and I am displaying 3 columns of strings in each. I also have the full row select on. I want to be able to double click on one of the rows, and have it return the string in the 3rd column. I've tried to look everywhere for a solution to this, but so far nothing comes up.

My code so far is:

private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
    MessageBox.Show(songList.SelectedItems[2].ToString());
}

Yet it returns an error saying "InvalidArgument=Value of '2' is not valid for 'index'. Parameter name: index"

You could try:

if (songList.SelectedItems.Count > 0) 
{
    ListViewItem item = songList.SelectedItems[0];
    string s_you_want = item.SubItems[1].Text;
}

Taken a ListViewItem , you can take columns values using SubItems[] property.

SelectedItems returns a SelectedListViewItemCollection and with the indexer you are accessing elements in this collection, ie ListViewItems, not the columns. this means that if you have a single row selected the collection contains only one item, and trying to access the third one gives you the error.

Try (edit according to Marco's comment):

songList.SelectedItems[0].SubItems[1].Text

I think that you hould bound not your listView to doubleClick event, but listViewItem. sender will have DataContext, from which you can get your third column.

How do you fill the ListView ? Wihtout knowing this, it's difficult to help. May be you could try this:

Set a breakpoint in this line:

MessageBox.Show(songList.SelectedItems[2].ToString());  

As soon as the debugger hits the breakpoint you could select songList and hit Shift-F9.
Now you can explore the songList and check yourself how to get the string of the third column.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM