无法检索列表视图的总索引

Cannot retrieve total indexof listview

我有一个 ListView 控件,我使用 TextBox 从中过滤结果。该代码用于突出显示匹配结果的背景色,但我想获得找到的总数 results/highlighted 个对象作为 int。现在填充的 int 不正确,与 found/highlighted 结果不一致。

如何获得 found/highlighted 个结果的总数?

private void textBox1_TextChanged(object sender, EventArgs e)
    {

        foreach (ListViewItem lvi in this.browserlistview.Items)
        {

            if (textBox1.TextLength > 0)
            {


                if (lvi.Text.IndexOf(textBox1.Text, StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    Color b = Color.Cyan;
                    lvi.BackColor = b;

                    foundobjlbl.Text = "Objects found: " + lvi.Text.IndexOf(textBox1.Text, StringComparison.InvariantCultureIgnoreCase).ToString(); 
                   //this is turning up incorrect integers

                }

                else
                {
                    Color w = Color.White;
                    lvi.BackColor = w;

                }

            }

            else if (textBox1.TextLength == 0)
            {
                Color w = Color.White;
                lvi.BackColor = w;

                foundobjlbl.Text = "Objects found : 0";
            }
        }
    }

有人看到我哪里出错了吗?

您正在将计数设置为您在特定项目中查找的文本的索引。因此,您为找到的每个项目设置一次,因此您将获得的是您的搜索词在找到的最后一个项目中的索引。

你想要的是跟踪找到的项目的数量并在搜索完成后设置它,所以像这样(我省略了大部分其他实现细节):

var foundCount = 0;

foreach (var item in items)
{
    if (IsMatch(item))
    {
        // set colour
        foundCount++;
    }
    else
    { 
        // set white
    }
}

foundobjlbl.Text = $"Objects found {foundCount}";