简体   繁体   中英

Listview selectedItem

How do I use the ListView 's ItemSelectionChanged event? I have a ListView , which in turn has 8 columns; and the first column of each row contains the Id for the row and this is what I'm after.

I need this because the Id is to be used to select info from a list. This list is what populates the ListView , but it doesn't show all of the info. The info not being shown is to be displayed in a RichTextBox and, of course, it should display the info for that selected item in the ListView . The Id's are the same, of course, but no matter what I try I can't seem to reach that value.

My code so far:

foreach ([ClassName] x in [List])
{
    if (x.id == Convert.ToInt32(myListView.FocusedItem.Text))
    {
        rtbxSpecific.Text = x.name;
    }
}

This works great for the first object in the ListView , but not for any of the following where it throws a NullReferenceException . Why does this happen? It's like the event fires, but it doesn't know about any other item in the list except for the first one.

I've also tried using selectedItems[0].Text , selectedItems[0].SubItems[0].Text but it's basically the same fault. This is really annoying me and I would be really thankful if someone could explain why it works for the first ListViewItem , but not the following.

I even tried using Find(...) on the list with:

[Class] cl = [List].Find(delegate([Class] q) {return q.id == Convert.ToInt32(myListView.FocusedItem.SubItems[0].Text);});

But no dice, which leads me to believe its the FocusedItem that is being nasty right now and I'm not getting anywhere with this. The Find(...) method would be cleaner to use, I suppose, but right now I'm getting the same error with both.

Simple check to see if the selected item.count was > 0.

if (myListView.SelectedItems.Count > 0)
{
    foreach ([Class] cl in [List])
    {
        if (myListView.SelectedItems[0].SubItems[0].Text == cl.[Field].ToString())
        {
            RichTextBox.Text = cl.[Field];
        }
    }
}

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