advanced web statistics

Use C# Modulus Operator to Determine Even or Odd Numbers

9/6/2006 2:28:41 PM

In creating a custom user control for a smart-client today I stumbled across what I think is a very simple gem for determining if an integer is even or odd.  This makes sense for alternating row background colors when rolling your own controls.

You wouldn't believe the other methods I have seen people use!  Here is a snippet of what I am trying to accomplish.

The code uses C#'s Modulus Operator (%). How this works is the operator computes the remainder after it divides it's first operand by the second.  In the case below, the number of controls (i.e. count) is divided by 2.  If it's an even-numbered row there won't be a remainder and if it's an odd-numbered row....

if(_pnlMenuItems.Controls.Count % 2 == 0)
{
   newMenuItem.BackColor = System.Drawing.Color.LightBlue;
}
else
{
   newMenuItem.BackColor = System.Drawing.SystemColors.Window;
}

C#, Code

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!