Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET email client alternate tr row colors based on even / odd

Tags:

html

c#

css

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 Wrong

like image 457
ondrovic Avatar asked Oct 26 '25 16:10

ondrovic


2 Answers

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++;
}
like image 62
lincolnk Avatar answered Oct 29 '25 04:10

lincolnk


Have considered something simpler using CSS like:

<style>
tr {
    color: blue;
}
tr:nth-child(odd) {
    color: green;
}
tr:nth-child(even) {
    color: red;
}
 </style>
like image 23
Dalorzo Avatar answered Oct 29 '25 06:10

Dalorzo