How to show a floating DIV over GridView row on Mouse over

← PrevNext →

Last update: 11th March 2023

We all know how important an Asp.Net GridView control is, in terms of its usefulness. In one of my previous articles, I have written on How to highlight GridView row on mouse over. In this article, (taking cue from the previous example) I’ll show you how to show a "floating" DIV next to each Row of the GridView on mouse over.

show floating div over gridview row on mouseover

Why do we need a Floating DIV?

Each row of the GridView control shows data extracted from a database table. For obvious reasons, we usually display limited or important data in a particular row. Therefore, we can use a DIV element as a container to show the remaining data when the user rolls the mouse over a row. The container (DIV) can have other purposes related to the contents of each row, like, sending an Email to individual Employees.

So, let us find out how we can achieve this.

The Markup and CSS
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        <!--style for gridview and the floating DIV-->
        .grid  
        {
            width: 100%; 
            font-size: 15px;
            background-color: #fff;
            border: solid 1px #525252;
        }
        
        .grid td 
        {
            padding:3px 5px;
            border:solid 1px #C1C1C1;
            color:#333;
            text-align:left;
        }
        
        .grid th { padding: 3px; color: #fff; 
            background: #424242 url(grd.png) repeat-x top; 
            border-left: solid 1px #525252;
            text-align: center; 
            text-transform: capitalize;}
        
        h3 {
            font-size:18px;
            color:#555;
            text-decoration:underline;
            margin:0 0 10px 0;
        }
        
        #divDetail  
        {
            float:left;
            font:inherit;
            font-size:13px;
            padding:0px 5px;
            width:auto;
            border:solid 1px #CCC; 
            display:none;
            color:#333;
            background:#d8e0e5;
        }
        
        #divDetail p { margin:0; }
        
        #divDetail a  
        {
            float:right;
            background-color:#357AE8;
            color:#FFF;
            text-decoration:none;
            border:solid 1px #2F5BB7; 
            border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; 
            padding:3px;margin:10px 0;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div id="divGrid">
            <h2>LIST OF EMPLOYEES</h2>
            <%--THE DATABOUND GRIDVIEW CONTROL.--%>
            <asp:GridView ID="gvEmployee" 
                AutoGenerateColumns="False"
                CssClass="grid" GridLines="None"
                cellpadding="3" runat="server">

                <Columns>
                    <asp:BoundField DataField="EmpID" HeaderText="Code" />
                    <asp:BoundField DataField="EmpName" HeaderText="Name" />
                    <asp:BoundField DataField="Country" HeaderText="Country" />
                    <asp:BoundField DataField="Email" HeaderText="Email Address" />
                </Columns>

                <HeaderStyle BackColor="Black" ForeColor="white" />

            </asp:GridView>
        </div>
        
        <%-- The floating DIV to show other employee details. --%>
        <%-- On mouseover event, it calls a JS function. --%>
        <div runat="server" id="divDetail" onmouseover="highlight(this, event)" 
            onmouseout="highlight(this, event)">
        </div>
    </form>
</body>
The Script
<script>
    // THE ROW INDEX OF THE GRIDVIEW, TO KEEP THE ROW HIGHLIGHTING
    // WHEN THE MOUSE IS ON ANOTHER CONTROL.
    var iRowIndex;

    function MouseEvents(objRef, evt, desc) {
        if (evt.type == "mouseover") {
            objRef.style.cursor = 'pointer'
            objRef.style.backgroundColor = "#EEE";
            showDiv(desc, evt.pageY);

        }
        else {
            objRef.style.backgroundColor = "#FFF";
            iRowIndex = objRef.rowIndex;
            HideDiv();
        }
    }
    function showDiv(desc, pos) {
        // SHOW THE DIV WITH DESCRIPTIONS NEXT TO THE SELECTED GRIDVIEW ROW.

        document.getElementById('divDetail').style.display = 'block';
        document.getElementById('divDetail').innerHTML = desc;
        document.getElementById('divDetail').style.marginTop = pos - 25 + 'px';
    }
    function HideDiv() { 
        document.getElementById('divDetail').style.display = 'none'; 
    }
    function highlight(objRef, evt) {
        if (evt.type == "mouseover") {
            objRef.style.display = 'block';
            document.getElementById('gvEmployee').rows[iRowIndex].style.backgroundColor = "#EEE";
        }
        else {
            if (evt.type == "mouseout") {
                document.getElementById('gvEmployee').rows[iRowIndex].style.backgroundColor = "#FFF";
                objRef.style.display = 'none';
            }
        }
    }
</script>
Code behind (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page 
{
    // SET THE CONNECTION STRING.
    string sCon = "Data Source=dna;Persist Security Info=False;Integrated Security=SSPI;" +
        "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;";

    protected void Page_Load(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection(sCon))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT EmpID, EmpName, " +
                "Country, Email FROM dbo.EmployeeDetails"))
            {
                SqlDataAdapter sda = new SqlDataAdapter();
                try
                {
                    cmd.Connection = con;
                    con.Open();
                    sda.SelectCommand = cmd;

                    DataTable dt = new DataTable();
                    sda.Fill(dt);

                    // BIND DATABASE WITH THE GRIDVIEW.
                    gvEmployee.DataSource = dt;
                    gvEmployee.DataBind();

                }
                catch (Exception ex)
                {  //  }
            }
        }
    }

    protected void gvEmployee_RowDataBound(object sender,
        System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        // BIND DATA WITH EACH ROW.
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            String sDetails = System.String.Empty;
            sDetails = "<span><h3>OTHER DETAILS</h3></span>";

            using (SqlConnection con = new SqlConnection(sCon))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT PresentAddress, Area, City " +
                    "FROM dbo.EmployeeDetails WHERE EmpID = " + 
                        DataBinder.Eval(e.Row.DataItem, "EmpID").ToString()))
                {
                    SqlDataAdapter sda = new SqlDataAdapter();
                    try
                    {
                        cmd.Connection = con;
                        con.Open();
                        sda.SelectCommand = cmd;

                        DataTable dt = new DataTable();
                        sda.Fill(dt);

                        if (dt.Rows.Count > 0)
                        {
                            sDetails = sDetails + "<p><strong>Employee Code: </strong>" +
                                DataBinder.Eval(e.Row.DataItem, "EmpID").ToString() + "</p>";
                            sDetails = sDetails + "<p><strong>Present Address: </strong>" +
                                dt.Rows[0]["PresentAddress"] + "</p>";
                            sDetails = sDetails + "<p><strong>Area: </strong>" + dt.Rows[0]["Area"] + "</p>";
                            sDetails = sDetails + "<p><strong>City: </strong>" + dt.Rows[0]["City"] + "</p>";
                            sDetails = sDetails + "<a href=?id=" + 
                                DataBinder.Eval(e.Row.DataItem, "EmpID").ToString() + " title=Send Mail>Send Mail</a>";

                            // BIND MOUSE EVENT (TO CALL JAVASCRIPT FUNCTION), WITH EACH ROW OF THE GRID.
                            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event, '" + sDetails + "')");
                            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event, '" + 
                                DataBinder.Eval(e.Row.DataItem, "EmpID").ToString() + "')");
                        }
                    }
                    catch (Exception ex)
                    { // }
                }
            }
        }
    }
}
Code behind (Vb.Net)
Option Explicit On
Imports System.Data                     ' FOR "DataTable"
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If Not IsPostBack Then

            Dim dt As DataTable = New DataTable

            Using con As SqlConnection = New SqlConnection("Data Source=dna;Persist Security Info=False;" & _
                "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;")

                Dim sQuery As String = "SELECT EmpID, EmpName, Country, Email FROM dbo.EmployeeDetails"

                Using cmd As SqlCommand = New SqlCommand(sQuery)
                    Dim sda As SqlDataAdapter = New SqlDataAdapter
                    cmd.Connection = con : con.Open()
                    sda.SelectCommand = cmd
                    sda.Fill(dt)

                    With gvEmployee
                        .DataSource = dt        ' BIND DATABASE WITH DataGridView.
                        .DataBind()
                    End With
                End Using
            End Using
        End If
    End Sub

    Protected Sub gvEmployee_RowDataBound(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvEmployee.RowDataBound

        ' BIND DATA WITH EACH ROW.

        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim sDetails As String = "<span><h3>Other Details</h3></span>"

            Dim dt As DataTable = New DataTable

            Using con As SqlConnection = New SqlConnection("Data Source=dna;Persist Security Info=False;" & _
                "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;")

                Dim sQuery As String = "SELECT PresentAddress, Area, City FROM dbo.EmployeeDetails " & _
                    "WHERE EmpID = " & e.Row.DataItem("EmpID").ToString

                Using cmd As SqlCommand = New SqlCommand(sQuery)

                    Dim sda As SqlDataAdapter = New SqlDataAdapter
                    cmd.Connection = con : con.Open()
                    sda.SelectCommand = cmd
                    sda.Fill(dt)

                    If dt.Rows.Count > 0 Then
                        sDetails = sDetails & "<p><strong>Employee Code: </strong>" & _
                            e.Row.DataItem("EmpID").ToString & "</p>"
                        sDetails = sDetails & "<p><strong>Present Address: </strong>" & _
                            dt.Rows(0).Item("PresentAddress") & "</p>"
                        sDetails = sDetails & "<p><strong>Area: </strong>" & dt.Rows(0).Item("Area") & "</p>"
                        sDetails = sDetails & "<p><strong>City: </strong>" & dt.Rows(0).Item("City") & "</p>"
                        sDetails = sDetails & "<a href=?id=" & e.Row.DataItem("EmpID").ToString & " _
                            title=Send Mail>Send Mail</a>"

                        ' BIND MOUSE EVENT (TO CALL JAVASCRIPT FUNCTION), WITH EACH ROW OF THE GRID.
                        e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event, '" & sDetails & "')")
                        e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event, '" & _
                            e.Row.DataItem("EmpID").ToString & "')")
                    End If

                End Using
            End Using
        End If
    End Sub
End Class

The floating DIV allow us to show secondary data (if at all required). These data can be shown just next to the row on which the mouse is rolled. Also, if the user rolls the mouse on the DIV to click the Send Mail button, the row will be still be highlighted. However, we can achieve this with a little help from JavaScript. We need to write client side scripts to capture the "Mouse" movements and accordingly position and show the Floating DIV.

← PreviousNext →