ASP.Net Change ImageButton.ImageUrl on mouseOver

Go To StackoverFlow.com

0

I am learning ASP.Net. I have a dynamically created ImageButton that I would like to change the ImageURL for when the user hovers over the control. I have tried this but it does not work:

 imgStars.Attributes.Add("onmouseover", "this.src= '~/Images/4Stars.png'")

If I set the imgStars.ImageURL in the codebehind to ~/Images/4Stars.png it works. But it does not work in javascript.

Please help. I have tried searching for my answer for hours, but I do not have a clue what to do.

2012-04-04 01:51
by yerty
The tilde "~" is a special character used in path resolution on the *server. This kind of path will not work on the client (which is where the script will run). You'll need to render a path that the browser understands - xanadont 2012-04-04 02:57
That did the trick. I hate it when the answer is so simple. I changed '~/Images/4Stars.png' to 'Images/4Stars.png' and it worked. I am not sure how to mark your comment as the answer. If you do let me know. Thanks agai - yerty 2012-04-04 03:19


1

"xanadont" answered you right but your solution will not work for every scenario. To ensure that every relative directory will be usable by the client, use this code snippet:

imgStars.Attributes.Add("onmouseover", "this.src= '" + this.Page.ResolveClientUrl("~/Images/4Stars.png") + "'");
2012-04-04 03:50
by RichardB
Thanks for your help. but I get an error on "this" it says that it is undefined. I am coding in VB instead of C#. Would that make a difference - yerty 2012-04-04 22:06
Yes, it's a syntax difference. Use "Me" instead of "this - RichardB 2012-04-04 22:16
Thank you that did the tric - yerty 2012-04-05 00:24


0

in VB you should use the following code:

    *imgBtnRegister.Attributes.Add("onmouseover", "this.src='" + Page.ResolveClientUrl("~/Images/Register_2.jpg") + "'")
        imgBtnRegister.Attributes.Add("onmouseout", "this.src='" + Page.ResolveClientUrl("~/Images/Register_1.jpg") + "'")*

use *Page.ResolveClientUrl("~/Images/Register_2.jpg")* instead of *this.Page.ResolveClientUrl("~/Images/Register_2.jpg")*
2015-10-10 06:49
by Ashif Mahmud Chowdhury