Set listview cell color for specific words

0

I need to load specific data into the listview so the cell in question is formatted with color defined. The code below formats the entire line and needs to format only the defined cell.

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

What would the code look like to just format the cell?

    
asked by anonymous 25.06.2016 / 22:06

1 answer

0

Subitem formatting code

                                 lsvDados.UseItemStyleForSubItems = false;//para que a formataçao do item nao se propague ao subitem
                                 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;
                                 }
  

Also informed by @Emerson js,

     

Your code is correct, but you lacked a detail that makes the whole   difference: set the UseItemStyleForSubItems property.

     

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

     

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

     

MSDN Documentation - UseItemStyleForSubItems

     

In short:

     

When you populate the 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 Daí pode fazer a formatação normalmente.

Format subview listview

    
28.06.2016 / 17:47