0

I have a ListView control that I'm filtering results from with a TextBox. The code works for highlighting the backcolors of the matching results, but I want to get the total found results/highlighted objects as an int. The int that is populating now is incorrect and not in line with the found/highlighted results.

How can I get the total number of found/highlighted results?

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

Does anyone see where I'm going wrong?

EyeSeeSharp
  • 604
  • 1
  • 8
  • 21

1 Answers1

1

You're setting your count to the index of the text you're looking for in a specific item. So you're setting it once for each item you've found, so what you'll get is the index of your search term in the last item found.

What you want is to track the count of found items and set it once the search is finished, so something like this (I've left out most of the other implementation details):

var foundCount = 0;

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

foundobjlbl.Text = $"Objects found {foundCount}";
Charles Mager
  • 25,735
  • 2
  • 35
  • 45
  • Yup, this did it. In the back of my mind I was thinking of incrementing within the if statement, but I felt like that was going to be incorrect. Thank you for the visualization and explanation :) – EyeSeeSharp May 01 '16 at 16:10