【问题标题】:Trying to search ListView for subitems matching a string尝试在 ListView 中搜索匹配字符串的子项
【发布时间】:2013-07-31 15:28:59
【问题描述】:

我在通过 ListView 扫描以查找与给定字符串匹配的子项时遇到问题。这是我的代码:

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
    {
        string date = datePicker.Value.ToShortDateString();
        int count = Program.booker.listView.Items.Count;

        for (int i = 0; i < count; i++)
        {
            ListViewItem lvi = Program.booker.listView.Items[i];

            if (lvi.SubItems.Equals(date))
            {
                MessageBox.Show("Found!", "Alert");
                Program.booker.listView.MultiSelect = true;
                Program.booker.listView.Items[i].Selected = true;
            }
            else
            {
                MessageBox.Show("Nothing found for " + date, "Alert");
            }
        }
    }

ListView 位于 Booker 表单上,我从 Filter 类访问它。我想在整个 ListView 中搜索与我的日期字符串匹配的任何项目。谢谢!

【问题讨论】:

  • 这是 WPF 还是 Winforms?还有你当前的代码有什么问题,它不起作用,抛出错误吗?
  • Winforms。而且我的代码不起作用。它只搜索我的 ListView 中的第一列,而不搜索子项。
  • 您不应该为每个项目循环遍历SubItems 并检查所有项目吗?我在想lvi.SubItems.Equals(date) 正在尝试将指向集合的指针与日期匹配,这总是错误的。也许将Equals 更改为Contains
  • 我正在搜索一个字符串,Contains 接受一个SubItem 作为参数。
  • 您是否尝试将您的条件更改为lvi.SubItems.Any(item =&gt; item.Equals(date))?毕竟,您问的是 any 子项是否等于日期,而不是子项(作为集合)是否等于日期。

标签: c# winforms listview


【解决方案1】:

您可以使用FindItemWithText 方法。

ListViewItem searchItem = null;
int index = 0;
do
{
    if (index < Program.booker.listView.Items.Count)
    {
        //true = search subitems
        //last false param = no partial matches (remove if you want partial matches)
        searchItem = Program.booker.listView.FindItemWithText(date, true, index, false);
        if (searchItem != null)
        {
            index = searchItem.Index + 1;

             //rest of code
        }
    }
    else
        searchItem =null;

} while (searchItem != null);

【讨论】:

  • 太棒了,正是我想要的。但是当我有 2 个日期匹配时,为什么只选择了一行?
  • FindItemWithText 方法只会得到第一个结果。你可以做的是this overload 在一个循环中,在找到一个之后更新startIndex。我已经更新了答案,但代码未经测试(直接输入 SO),但希望能给你一个想法。
  • 编辑后的代码让我陷入了无限循环。我认为这是因为searchitem 在找到它的第一个实例后立即变为非空。
  • @RyanCohen - 尝试将其设置为 index + 1
  • 我收到一个错误,Value of '2' is not valid for 'startIndex'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多