C# VB .NET: why the fore/back color setting of ListView SubItem does not work?

Posted by NosaLee in .NET Programming on 29-06-2012. Tags: , , , , , , , , , , ,

Author: Nosa Lee
Original Address: http://www.seeksunslowly.com/c-sharp-vb-net-why-the-foreback-color-setting-of-listview-subitem-does-not-work
To reprint this article, please indicate the source, thank you.

Today I need to set the foreground color for a SubItem in a Details ListView, lucky, ListViewSubItem class has the ForeColor property, so I wrote the following code:

lvi.SubItems(2).ForeColor = Color.Red ‘ lvi is a ListViewItem object.

Unfortunately, it does not work, and I had tried to call ListView.Refresh following above code, no luck also. So, I tried to research all the properties and methods of ListView, ListViewItem and ListViewSubItem classes. Hard work pays off, after a few minutes, I found ListViewItem class has the UseItemStyleForSubItems property, it seems to be used in this case, and the default value is Ture. So, I tried to change it to False in my code, it works – the foreground color of ListViewSubItem appeared, and do not need to call ListView.Refresh, sample code as below:

Dim lvi As ListViewItem
lvi = lv.Items.Add("Test") ' lv is ListView object.
lvi.UseItemStyleForSubItems = False
lvi.SubItems.Add "Failed"
lvi.SubItems(1).ForeColor = Color.Red

Post a comment