3

I need to check if an item with a particular name exists in the CheckedItems collection of a ListView.

So far I've tried:

ListViewItem item = new ListViewItem(itemName);

if (listView1.CheckedItems.IndexOf(item) >= 0)
   return true;

and

ListViewItem item = new ListViewItem(itemName);

if (listView1.CheckedItems.Contains(item))
   return true;

Neither of those worked. Is there a way to do this without looping through CheckedItems and checking them one by one?

4

3 回答 3

1

Get rid of newing up a ListViewItem and do this instead:

ListViewItem itemYouAreLookingFor = listView1.FindItemWithText("NameToLookFor");

// Did we find a match?
if (itemYouAreLookingFor != null)
{
    // Yes, so find out if the item is checked or not?
    if(itemYouAreLookingFor.Checked)
    {
        // Yes, it is found and check so do something with item here
    }
}
于 2013-09-03T21:24:09.780 回答
1

You can benefit LINQ for this purpose:

bool itemChecked =  listView1.CheckedItems.OfType<ListViewItem>()
                             .Any(i => i.Text == itemText);
//You can also retrieve the item with itemText using FirstOrDefault()
var checkedItem = listView1.CheckedItems.OfType<ListViewItem>()
                                        .FirstOrDefault(i=>i.Text == itemText);
if(checkedItem != null) { //do you work...}

You can also use the ContainsKey to determine if the item (with name being itemName) is checked:

bool itemChecked = listView1.CheckedItems.ContainsKey(itemName);
于 2013-09-04T10:45:30.980 回答
0

Using new, you are creating a new item which is not added to the list view (since it is new) and can therefore not be found when using listView1.Contains(item).

When you add an item, use a key/value pair and use contains on the values.

于 2013-09-03T21:20:23.010 回答