Trying to get the color to alternate colors based on even / odd in c# using inline css
sb.AppendLine("<table width='100%' border='0' align='center' cellpadding='5' cellspacing='0' style='font-family:arial,helvetica,sans-serif;'><tbody><tr><td style='padding:5px;background-color:rgb(169, 169, 169);color:white;'>Filenames</td></tr>");
foreach (var item in logList)
{
sb.AppendLine("<tr><td style='background-color:#55bada;'>" + Path.GetFileName(item) + "</td></tr>");
sb.Append("</tr></tbody></table>");
}
I have tried the following but it seems to duplicate the data and not shift the coloring evenly
sb.AppendLine("<table width='100%' border='0' align='center' cellpadding='5' cellspacing='0' style='font-family:arial,helvetica,sans-serif;'><tbody><tr><td style='padding:5px;background-color:rgb(169, 169, 169);color:white;'>Filenames</td></tr>");
int count = 0;
foreach (var item in logList)
{
for (count = 0; count <= logList.Count; count ++)
{
if (count % 2 == 0)
{
count += 1;
sb.AppendLine("<tr><td style='background-color:#bada55;'>" + Path.GetFileName(item) + "</td></tr>");
}
else
{
count -= 1;
sb.AppendLine("<tr><td style='background-color:#55bada;'>" + Path.GetFileName(item) + "</td></tr>");
}
}
}
sb.Append("</tr></tbody></table>");
Check Even Odd

You're doing an extra loop for no reason. Iterate your items once and increase your counter once per item.
int count = 0;
foreach (var item in logList)
{
if (count % 2 == 0)
{
sb.AppendLine("<tr><td style='background-color:#bada55;'>" + Path.GetFileName(item) + "</td></tr>");
}
else
{
sb.AppendLine("<tr><td style='background-color:#55bada;'>" + Path.GetFileName(item) + "</td></tr>");
}
count++;
}
Have considered something simpler using CSS like:
<style>
tr {
color: blue;
}
tr:nth-child(odd) {
color: green;
}
tr:nth-child(even) {
color: red;
}
</style>
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