Friday, May 18, 2012

How to add customized tooltip to a gridview row and change hovred row colour.

In Page.aspx, put these line of codes to add a div and label. Label will store the value to show in ToolTip and div will work as a container. You can bind any value in this label from table or in run time and can change CssClasses as per your requirement :

<div id="divComments" runat="server" class="TooltipDiv"  style="display:none;"> 
<asp:Label runat="server" ID="lblComments" Text='<%#DataBinder.Eval(Container.DataItem,"Comments") %>' CssClass="TooltipText"></asp:Label></div>

Now put these java script functions to page to handle mouse out and hover event:

function showToolTip(divId, linkId) {
            if (null != divId) {
                var elementRef = document.getElementById(divId);
                if (elementRef != null) {
                    elementRef.style.position = 'absolute';
                    elementRef.style.left = event.clientX + 5 + document.body.scrollLeft;
                    elementRef.style.top = event.clientY + 5 + document.body.scrollTop;
                    elementRef.style.visibility = 'visible';
                    elementRef.style.display = 'block';
                }
                if (null != linkId) {
                    var elementBak = document.getElementById(linkId);
                    if (elementBak != null) {
                        elementBak.style.backgroundColor = '#d9d9d9';
                    }
                }
            }
        }

        function hideToolTip(divId, linkId) {
            if (null != divId) {
                var elementRef = document.getElementById(divId);
                if (elementRef != null) {
                    elementRef.style.visibility = 'hidden';
                }
            }
            if (null != linkId) {
                var elementBak = document.getElementById(linkId);
                if (elementBak != null)
                {
                    elementBak.style.backgroundColor = '#ffffff';
                }
            }
        }

After this put these code in the grdView_RowDataBound event within Page.aspx.cs, it will find current row and call this java script function for it. :

HtmlContainerControl addToolTipDiv = (HtmlContainerControl)e.Row.FindControl("divComments");
                        e.Row.Attributes.Add("onmouseover", "showToolTip('" + addToolTipDiv.ClientID + "','" + e.Row.ClientID + "');");
                        e.Row.Attributes.Add("onmouseout", "hideToolTip('" + addToolTipDiv.ClientID + "','" + e.Row.ClientID + "');");

If you want to add only background change of hovered row then call it in this way. It will pass no div Id so there will be no tool tip added.

e.Row.Attributes.Add("onmouseover", "showToolTip('" + " "+ "','" + e.Row.ClientID + "');");
  e.Row.Attributes.Add("onmouseout", "hideToolTip('" +" " + "','" + e.Row.ClientID + "');");

No comments:

Post a Comment