Set listview cell color for specific words

Asked

Viewed 745 times

0

I need that when loading specific data in the listview the cell in question is formatted with defined color. The code below formats the entire and accurate row that 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 the code would look like to format only the cell ?

1 answer

0


Code for formatting the subset

                                 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 it lacked a detail that makes all the difference: set Useitemstyleforsubitems property.

When you create your items to popular the Listview they must have the Useitemstyleforsubitems property set to false.

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

MSDN Documentation - Useitemstyleforsubitems

In short:

When popular 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 subitem listview

Browser other questions tagged

You are not signed in. Login or sign up in order to post.