I have a Windows Form application in which I have a ListView
control. I want to change the forecolor of a single subitem. Although I have managed to change the color of a entire row or column, I haven't figured out a way to do this for a single subitem. Does anyone know of a way to do this?
The solution is fairly simple, and is indicated in the Remarks section of the documentation for the ListViewSubItem.ForeColor
property:
If the
UseItemStyleForSubItems
property of theListViewItem
that owns the subitem is set to true, setting this property has no effect.
The default setting is intended to maintain a consistent appearance for all subitems owned by a single item in a ListView
control so that you only have to change the properties in one place. To change the default behavior, you need to set the UseItemStyleForSubItems
property of a particular ListViewItem
to "False".
Once you've done that, you can adjust the ForeColor
(or any other) property of an individual subitem. For example:
myListView.Items[0].UseItemStyleForSubItems = false;
myListView.Items[0].SubItems[1].ForeColor = Color.Red;
A way would be to set the color for all the subitems and change for the one you want.
Example code:
private void btn_Add_Click(object sender, EventArgs e)
{
ListViewItem lvi = new ListViewItem();
ListViewItem.ListViewSubItem lvsi1 = new ListViewItem.ListViewSubItem();
ListViewItem.ListViewSubItem lvsi2 = new ListViewItem.ListViewSubItem();
lvi.Text = tb_Main.Text;
lvsi1.Text = tb_Sub1.Text;
lvsi2.Text = tb_Sub2.Text;
lvi.UseItemStyleForSubItems = false;
lv_List.ForeColor = Color.Black;
if (lvsi1.Text == tb_Different.Text)
{
lvsi1.ForeColor = Color.Red;
}
if (lvsi2.Text == tb_Different.Text)
{
lvsi2[2].ForeColor = Color.Red;
}
lv_List.Items.Add(lvi);
lvi.SubItems.Add(lvsi1);
lvi.SubItems.Add(lvsi2);
}
This example will color every sub Item that has the value "Monday"
public static void colorList(ListView lsvMain)
{
foreach (ListViewItem lvw in lsvMain.Items)
{
lvw.UseItemStyleForSubItems = false;
for (int i = 0; i < lsvMain.Columns.Count; i++)
{
if (lvw.SubItems[i].Text.ToString() == "Monday")
{
lvw.SubItems[i].BackColor = Color.Red;
lvw.SubItems[i].ForeColor = Color.White;
}
else {
lvw.SubItems[i].BackColor = Color.White;
lvw.SubItems[i].ForeColor = Color.Black;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With