Thursday, September 6, 2007

Setting image swap on your asp.NET Image Controls

In this article, I wanted to archive a clean and quick way of adding mouse rollover image swapping to your asp.net (2.0) forms. Before you wonder why you wasted the last 20 seconds of your life, I'll show you in part 2 how to wrap it up into a class to make it more object oriented by developing a reusable mouse rollover control.

It would be really great if the .net HyperLink control simply had an ImageRolloverUrl property, to go along with its ImageUrl property (maybe in 3.0?). At that point, we'd be done, and you'd be back to reading about my cat (I don't own a cat, but somehow writing about your black lab seems even lamer).

Moving on, since we'll have to wrap our HyperLink control around an Image control, you'll notice I don't even set the ImageUrl property of HyperLink. Therefore, it will look like this:

<asp:HyperLink id="lnkPage1" runat="server" >
<asp:Image id="imgMyImage" runat="server" ImageUrl="~/App_Themes/Default/Images/my_image.png" />
</asp:HyperLink>


in the code behind:

string imgPath = "~/images/yourimage.png";
string imgPathOver = "~/images/yourimage_over.png";

lnkControl.Attributes.Add("onmouseover", "document.getElementById('" + imgControl.ClientID + "').src='" + imgPathOver + "';");

lnkControl.Attributes.Add("onmouseout", "document.getElementById('" + imgControl.ClientID + "').src='" + imgPath + "';");

So, pretty simle in all, though it's still just a little more code than a developer might be willing to write for each image link. That's why I'll show you in part 2 how I chose to wrap this in a Class for reusibility across your application(s).


No comments: