Format listview subitem

1

I have trouble setting the background color of the listview SubItem when returning query from the database. I need in column # 18, which will return values such as "Overdue" and "On Day", when the value returned is="Overdue" that subitem in column 18 is red background. The code below colors the full line.

foreach (ListViewItem item in lsvDados.Items)
                {
                    if (item.SubItems[18].Text == "VENCIDO") 
                    item.BackColor = System.Drawing.Color.Red;
                    else item.BackColor = System.Drawing.Color.Green;
                }

The code below does not color anything.

foreach (ListViewItem item in lsvDados.Items)
                {
                     if (item.SubItems[18].Text == "Vencido") 
                     item.SubItems[18].BackColor = System.Drawing.Color.Red;

                     else 
                     item.SubItems[18].BackColor =System.Drawing.Color.Green;
                 }

How do I color only the sub item with the desired value? How would the code to scan all the listview look for some subitem with this desired value and soon after finding format it?

    
asked by anonymous 28.06.2016 / 11:53

1 answer

1

Your code is correct, but one detail missing makes all the difference: set the UseItemStyleForSubItems property.

When you create your items to popular ListView they should have the UseItemStyleForSubItems property set to false .

When the value is true , each SubItem will have the same style set to Item , even if you change its background color, font, etc ...

MSDN Documentation - UseItemStyleForSubItems

In short:

  • When you use ListView do:

        ListViewItem i1 = new ListViewItem("1");
    
        i1.SubItems.Add("Valor Coluna 1...");
        i1.SubItems.Add("Valor Coluna 2...");
        i1.UseItemStyleForSubItems = false; // para cada item
    

Then you can do the formatting normally.

    
28.06.2016 / 13:17