سؤال

I want to find a certain string (text) that is entered in the textBox1 field in the listView1. So the current problem is, the code below works however right next to the item which has its backcolor changed, the other item would have the same backcolor when hovered over. And when the row is selected then hovered over, there is change in colors (the dark blue goes a bit light when hovered).The listView is kept inside a tabControl. Any ideas why the item next to it gets the backcolor? Any solutions would be great.

foreach (ColumnHeader sColumnHeader in listView1.Columns)
{
    foreach (ListViewItem items in listView1.Items)
    {
        if (items.SubItems[sColumnHeader.Index].Text == textBox1.Text)
        {
            listView1.Items[items.Index].UseItemStyleForSubItems = false;
            listView1.Items[items.Index].SubItems[sColumnHeader.Index]
                                        .BackColor = Color.LightBlue;
         }
    }
}

Here is a link to the problem screenshot: http://i.stack.imgur.com/A7H7E.png

هل كانت مفيدة؟

المحلول 3

The problem was due to the activation on the listView being on "OneClick".

Resetting it back to Standard fixed this problem.

Sorry and thanks to everyone who has helped.

نصائح أخرى

UPDATE Use this Code

       foreach (ColumnHeader sColumnHeader in listView1.Columns)
        {
            foreach (ListViewItem item in listView1.Items)
            {
                if (item.SubItems[0].Text == textBox1.Text)
                {
                    listView1.Items[item.Index].UseItemStyleForSubItems = false;
                    listView1.Items[item.Index].SubItems[0]
                                                .BackColor = Color.LightBlue;
                }
            }
        }

[This is not really meant as an answer, but it's too long for a comment]

Your code as shown works perfectly for me -- the subitem that matches the text in textBox1 has its background changed to LightBlue. If the colour changes on selection or hovering, that has nothing to do with this particular bit of code.

Obviously, if you have FullRowSelect set to true, the background will change when the row is selected.

BTW, you should use much less indexing -- instead just iterate the Items and SubItems collections:

foreach (ListViewItem item in listView1.Items)
{
    foreach (ListViewItem.ListViewSubItem subItem in item.SubItems) 
    {
        if (subItem.Text == textBox1.Text)
        {
            item.UseItemStyleForSubItems = false;
            subItem.BackColor = Color.LightBlue;
        }
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top