【问题标题】:ListView CheckedItems find item by nameListView CheckedItems 按名称查找项目
【发布时间】:2013-09-03 21:12:45
【问题描述】:

我需要检查具有特定名称的项目是否存在于 ListView 的 CheckedItems 集合中。

到目前为止我已经尝试过:

ListViewItem item = new ListViewItem(itemName);

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

ListViewItem item = new ListViewItem(itemName);

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

这些都不起作用。有没有一种方法可以做到这一点,而无需遍历 CheckedItems 并逐个检查它们?

【问题讨论】:

    标签: c# winforms listview


    【解决方案1】:

    您可以为此受益LINQ

    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...}
    

    您还可以使用ContainsKey 来确定项目(名称为itemName)是否被选中:

    bool itemChecked = listView1.CheckedItems.ContainsKey(itemName);
    

    【讨论】:

    • 当我将i.Name 更改为i.Text 时,上述LINQ 方法有效。如果您更新答案,我会将其标记为已接受。
    • @Dr.Greenthumb 那是因为您在问题中说with a particular name exists,当然如果您的意思是Text,将其更改为Text 会起作用。如果是这样,则不能使用 ContainsKey,因为它用于 Name 而不是 Text
    • 我最初以为可以通过名称找到它,但是当我将listView1.CheckedItems添加到手表时,没有name参数。你也是对的,ContainsKey 在我尝试的时候没有用。
    【解决方案2】:

    摆脱新的ListViewItem 而是这样做:

    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
        }
    }
    

    【讨论】:

      【解决方案3】:

      使用 new,您正在创建一个未添加到列表视图中的新项目(因为它是新的),因此在使用 listView1.Contains(item) 时无法找到。

      添加项目时,使用键/值对并在值上使用 contains。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-02
        • 2016-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-19
        相关资源
        最近更新 更多