Format subitem listview

Asked

Viewed 338 times

1

I have problems defining Subitem background color from listview when returning database query. I need that in the column n° 18, which will return values such as " Expired" and " In Day" when the returned value is = the "Expired" that ascend in column 18 is red. The code below colors the complete 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 just the subitem with the desired value ? How would the code look to scan the entire listview looking for some subitem with this desired value and soon after find format it ?

  • @Emerson JS, The code formats only one value returned from the database. If select returns 3 lines, only 1 will be formatted. Because this occurs, should format all lines.

1 answer

1


Your code is correct, but it lacked a detail that makes all the difference: configure the property UseItemStyleForSubItems.

When you create your items to popular the ListView they must have the property UseItemStyleForSubItems configured to the value 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 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
    

Then you can do the formatting normally.

  • @ Emerson I get it, I’m going to apply this property, now it’s clear. Thank you very much

Browser other questions tagged

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