Monday, March 24, 2008

Neat way to hover in .NET

I figured out a neat way to set an onMouseOver and onMouseOut property to a gridview with alternating colors. This way, you don't have to figure out background colors and such.

//Add onMouseOver/onMouseOut Functionality
if ((e.Row.RowIndex % 2) == 1)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor = 'Grey'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor = 'White'");
}
else if ((e.Row.RowIndex % 2) == 0)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor = 'Grey'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor = 'LightGrey'");
}

The % (modulus) returns any remainders of the e.Row.RowIndex being divided by 2. If there is a remainder, then it is odd, if not, even. You now know what color your rows BG should be on the onMouseOut. Nifty.

EDIT: The if statements really aren't clear and they actually do the opposite of what they look like they are doing. If e.Row.RowIndex % 2 returns a remainder, it returns false (0). If it doesn't return a remainder, it returns true (1).

No comments:

Post a Comment