I tryed to add different colors rows and columns on listview.
Firstly i used these codes
foreach (ListViewItem item in listView.Items)
{
item.BackColor = item.Index % 2 == 0 ? Color.FromArgb(70, 70, 70) : Color.FromArgb(61, 61, 61);
}
Then the listview shown like this
And then i tryed these codes:
foreach (ListViewItem item in listView.Items)
{
item.SubItems[2].BackColor = Color.FromArgb(18, 64, 100);
item.SubItems[9].BackColor = Color.FromArgb(105, 16, 38);
item.UseItemStyleForSubItems = false;
}
Ande last listview shown like this
Whats wrong?
thank you.
CodePudding user response:
When you apply alternating row colors, you only apply that to column 1 (aka. item
). When you apply the column[2 and 9] formatting, you turn off UseItemStyleForSubItems
, so only the first column now carries the alternating row colors. You have to combine the alternating row and column formating code into one code block like so:
foreach (ListViewItem item in listView.Items)
{
//Disable item styles for sub items so we can apply column colors.
item.UseItemStyleForSubItems = false;
//Create the main colors used for row formatting.
Color a = Color.FromArgb(61, 61, 61);
Color b = Color.FromArgb(70, 70, 70);
//Create the alternate colors used for column 2 and 9.
Color alt2 = Color.FromArgb(18, 64, 100);
Color alt9 = Color.FromArgb(105, 16, 38);
//Apply colors to column 1
if (item.Index % 2 == 0) {
item.BackColor = b;
} else {
item.BackColor = a;
}
//Loop through the sub items and apply colors.
foreach(ListViewSubItem sub in item.SubItems) {
if (sub.Index == 2) { //Apply column 2 color.
sub.BackColor = alt2;
} else if (sub.Index == 9) { //Apply column 9 color.
sub.BackColor = alt9;
} else if (item.Index % 2 == 0) { //Apply alt row color.
sub.BackColor = b;
} else { //Apply main row color. This is the default.
sub.BackColor = a;
}
}
}
CodePudding user response:
I did with this codes.
foreach (ListViewItem item in listView.Items)
{
//Disable item styles for sub items so we can apply column colors.
item.UseItemStyleForSubItems = false;
//Create the main colors used for row formatting.
Color a = Color.FromArgb(61, 61, 61);
Color b = Color.FromArgb(70, 70, 70);
//Create the alternate colors used for column 2 and 9.
Color alt2 = Color.FromArgb(18, 64, 100);
Color alt9 = Color.FromArgb(105, 16, 38);
//Apply colors to column 1
if (item.Index % 2 == 0)
{
item.BackColor = b;
}
else
{
item.BackColor = a;
}
int i = 0;
foreach (ListViewSubItem sub in item.SubItems)
{
sub.Name = i.ToString();
i ;
}
foreach (ListViewSubItem sub in item.SubItems)
{
if (sub.Name == "3")
{ //Apply column 2 color.
sub.BackColor = alt2;
}
else if (sub.Name == "11")
{ //Apply column 9 color.
sub.BackColor = alt9;
}
else if (item.Index % 2 == 0)
{ //Apply alt row color.
sub.BackColor = b;
}
else
{ //Apply main row color. This is the default.
sub.BackColor = a;
}
}
listView.Sort();
}