I listed top 5 data by gridview. I use itemtemplate and hyperlink for them. An Idditon I have an Image. When I mouse over on hyperlink the image will be change. How can it ?

Dani AI

Generated

As described, the goal is swapping an image when the user hovers a HyperLink. The working pattern in this thread is correct: render a concrete client-side id and URL for each row, and let the browser run simple JS against those values. The "server tag is not well formed" error came from trying to put a databinding expression and quotes directly into a non-server attribute; ASP.NET's parser and attribute-quoting make that fragile. Setting the onmouseover/onmouseout in RowDataBound (or producing a single, fully-formed databinding string) avoids that parsing problem and ensures the page emits valid HTML/JS.

For a cleaner, more maintainable approach avoid inline onmouseover on every link. Put the hover URL into a data- attribute in the template and use one delegated event handler on the GridView container to swap the image. This keeps markup unobtrusive and performs better when there are many rows. If the hover image is static, consider a CSS :hover or sprite technique instead — no JS needed and no flicker.

Practical tips and gotchas:

  • Use the control's rendered id (ClientID) when calling document.getElementById, as corrected.
  • Build server-side URLs with ResolveClientUrl/ResolveUrl so paths are correct.
  • Preload hover images to avoid noticeable flicker.
  • Add keyboard support (onfocus/onblur or :focus styles) for accessibility.
  • If you must bind inline, generate one safe string (escape quotes) rather than embedding Eval inside raw attributes.

Example of the delegation idea (template stores data-hover and data-target):

<!-- in ItemTemplate: <a data-hover="images/hover.jpg" data-target="img42">Link</a> -->

<script>
document.getElementById('grid').addEventListener('mouseover', function(e){
  var a = e.target.closest && e.target.closest('a[data-hover]');
  if (!a) return;
  var img = document.getElementById(a.dataset.target);
  if (img) img.src = a.dataset.hover;
});
</script>

Recommended Answers

All 9 Replies

Hi Cano82,

You need to add some javascript in the "onMouseOver" event of the hyperlink that changes the image. Here is an example of a link and image, where mousing over the link changes the source of the image, and mousing out of the link changes the image back to the original:

<html>
    <head>
        <title>(Your title here)</title>
        <script type="text/javascript">
        <!--
        
            function changeImage(theElement, theNewImage)
            {
                document.getElementById(theElement).src = theNewImage;
            }
        
        // -->
        </script>
    </head>
    <body>
    
        <asp:HyperLink ID="HyperLink1" runat="server" Text="abc" NavigateUrl="~/anotherPage.aspx" onmouseover="changeImage('theImage', 'images/image2.jpg');" onmouseout="changeImage('theImage', 'images/image1.jpg');"></asp:HyperLink>
        <img id="theImage" src="images/image1.jpg" />
    
    </body>
</html>

~ mellamokb

I take this error: The server tag is not well formed.

I wrote this code:

<ItemTemplate>
<asp:HyperLink ID="HyperLinkMS" runat="server" Text='<%# Eval("Header") %>' onmouseover="changeImage('theImage', '<%# Eval("Picture") %>)';" />


</ItemTemplate>


and in code behind:


protected void Page_Load(object sender, EventArgs e)
{
HyperLink hp = (HyperLink)GridView1.FindControl("HyperLinkMS");
hp.Attributes.Add("onmouseover", "changeImage()");


}

The onMouseOver attribute is not part of the server-side tag, so it doesn't support DataBinding (<%# Eval("Picture") %>). However, you can use the GridView's RowDataBound event to access each HyperLink separately and set their onMouseOver attributes to the correct value as follows:

---- myPage.aspx ----

<asp:GridView .... OnRowDataBound="GridView1_RowDataBound">
...
  <ItemTemplate>
    <asp:HyperLink ID="HyperLinkMS" runat="server" Text='<%# Eval("Header") %>' />
    <asp:Image ID="ImageMS" runat="server" ImageUrl='<%# Eval("Picture") %>' />
  </ItemTemplate>
...
</asp:GridView>

---- ----

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.DataItem != null)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;
            HyperLink h = (HyperLink)e.Row.FindControl("HyperLinkMS");
            Image i = (Image)e.Row.FindControl("ImageMS");
            h.Attributes.Add("onmouseover", "changeImage('" + i.UniqueID + "', '" +
                 drv["PictureMouseOver"].ToString() + "');");
        }

    }

~ mellamokb

Thank you very much

I can not work the code :(. It is very urgently.

My mistake. Please change this code:

i.UniqueID

to the following:

i.ClientID

Then it should work. Please post back if you have any more problems.

~ mellamokb

Can you upload the source anywhere? I can not work the source

My simplest script that works:

Page source:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<html>
    <head>
        <script type="text/javascript">
        <!--
        
            function changeImage(theElement, theNewImage)
            {
                document.getElementById(theElement).src = theNewImage;
            }
        
        // -->
        </script>
    </head>
    
    <body>
        <form runat="server">
        <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:TemplateField>
                      <ItemTemplate>
                            <asp:HyperLink ID="HyperLinkMS" runat="server" Text='<%# Eval("Header") %>' NavigateUrl='<%# Eval("Link") %>' />
                            <asp:Image ID="ImageMS" runat="server" ImageUrl='<%# Eval("Picture") %>' />
                      </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        </form>
    </body>
</html>

code behind:

using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class test : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("Header");
        dt.Columns.Add("Picture");
        dt.Columns.Add("PictureMouseOver");

        dt.Rows.Add("Test 1", "images/cart.jpg", "images/filter.jpg");
        dt.Rows.Add("Test 2", "images/noFilter.jpg", "images/AddToCart.gif");

        GridView1.DataSource = dt;
        GridView1.DataBind();

    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.DataItem != null)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;
            HyperLink h = (HyperLink)e.Row.FindControl("HyperLinkMS");
            Image i = (Image)e.Row.FindControl("ImageMS");
            h.Attributes.Add("onmouseover", "changeImage('" + i.ClientID + "', '" +
                 drv["PictureMouseOver"].ToString() + "');");
        }

    }

}

You need to adjust the field names to suit your datasource, and you need to adjust the databinding code to wherever your data comes from.

~ mellamokb

Thank you very much mellamokb .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.