Click here to Skip to main content
15,884,629 members
Articles / Web Development
Tip/Trick

Simple Chart with ToolTip using ASP.NET Chart Control

Rate me:
Please Sign up or sign in to vote.
4.93/5 (5 votes)
25 Sep 2012CPOL2 min read 52.7K   1.6K   5   4
This article is to help beginners know how to create a customized tooltip on a bar chart

Introduction

Tooltips and charts are most commonly used in a number of web applications. Chart controls are of immense help while generating reports. Although there is a default tool tip available in ASP.NET there may be many a cases where tool tips needs to be customized in sink with our website. Combining chart control (here bar chart) with the tool tip provides great visualization of the chart data for the users.

Using the code

First we create a chart (bar) by using the ASP.NET chart control. It can be dragged and dropped from the toolbox under data category. Once it is done we will find the following code is being added to our .aspx page 

ASP.NET
<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

The next thing is to write the control code for our chart as follows:

XML
<asp:Chart ID="Chart1" runat="server" Width="500" Height="500">
 <Series>
  <asp:Series Name="Series1" ChartType="Column" >
  </asp:Series> 
 </Series>
 <ChartAreas>
   <asp:ChartArea Name="ChartArea1">   </asp:ChartArea>
 </ChartAreas>
</asp:Chart>

Now that our chart is being created our next step is to create the tooltip:

ASP.NET
<div id="myToolTip" style="position: absolute; visibility: hidden; width:200px; height:100px; margin: 18px 0;
            padding: 18px 20px;
            background-color: white; /* easy rounded corners for modern browsers */
            -moz-border-radius: 6px;
            -webkit-border-radius: 6px;
            border-radius: 6px;
            border: 1px solid #c5d9e8;
            padding: 17px 19px;">
<div style="position:absolute;float:left;">
<asp:Image ID="Image1" runat="server" ImageUrl="~/exclamation-mark.jpg" />
</div>
<div style="position:absolute;left:70px;top:30px;">
 <b><asp:Label ID="lbl" runat="server"></asp:Label></b>
</div>
<div style="position:absolute;top:60px;">
<asp:LinkButton ID="PDlink" runat="server" 
       OnClick="PDlink_Click">Click here</asp:LinkButton>
</div>
</div>   

Here I have customized the tool tip according to my style. You can change the CSS suitable to your preferred style.

The next steps is to write the JavaScript so that our tooltip works:

JavaScript
<script type="text/javascript">
    function showTooltip(value1, value2,ex) {
        var tooltip = document.getElementById("myToolTip");
        tooltip.style.visibility = "visible";
        var posx = 0;
        var posy = 0;
        if (!e) var e = (window.event) ? event : ex;
        if (e.pageX || e.pageY) {
            posx = e.pageX;
            posy = e.pageY;
            tooltip.style.left = posx + "px";
            tooltip.style.top = (posy-100)+ "px";
        }
        else if (e.clientX || e.clientY) {
            if (e.cancelBubble != null) e.cancelBubble = true;
            //for IE8 and earlier versions event bubbling occurs...
            posx = e.clientX + document.body.scrollLeft
                   + document.documentElement.scrollLeft;
            posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
            tooltip.style.left = posx + "px";
            tooltip.style.top = (posy-100)+ "px";
        }
        document.getElementById("<%=lbl.ClientID%>").innerHTML = 
          "X and Y Values : " +"("+value1+","+value2+")"; 
      }
      function hide() {
           var tooltip = document.getElementById("myToolTip");
           tooltip.style.visibility = "hidden";
      }
</script> 

The above code works properly for all the browsers. Now that we are done with .aspx page let look around our 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.Web.UI.DataVisualization;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using ChartToolTip.DataAccess;
using System.Data;
namespace ChartToolTip
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            #region using Database
            /*  FetchUserTimeDetails _obj = new FetchUserTimeDetails();
            DataTable Table=_obj.FetchUserTimeDetailsFromDB();
          
            Chart1.ChartAreas[0].AxisX.Title = "Username";
            Chart1.ChartAreas[0].AxisY.Title = "Hours Logged";
          
            Chart1.Series["Series1"].ChartType = SeriesChartType.Column;
          
          
            for(int i=0;i<Table.Rows.Count;i++)
            {
             Chart1.Series["Series1"].Points.AddXY(
               Table.Rows[i]["username"],Table.Rows[i]["total_hours_logged"]);
            }*/
            #endregion
            #region without using DataBase
            Chart1.ChartAreas[0].AxisX.Title = "X Axis";
            Chart1.ChartAreas[0].AxisY.Title = "Y Axis";
            List<int> list = new List<int>();
            list.Add(20);
            list.Add(30);
            list.Add(59);
            list.Add(30);
            list.Add(63);
            foreach (int value in list)
            {
                Chart1.Series["Series1"].Points.AddY(value);
            }
#endregion
            Chart1.Series["Series1"].Points[0].Color = Color.Red;
            Chart1.Series["Series1"].Points[0].IsValueShownAsLabel = true;
            Chart1.Series["Series1"].Points[1].Color = Color.RoyalBlue;
            Chart1.Series["Series1"].Points[1].IsValueShownAsLabel = true;
            Chart1.Series["Series1"].Points[2].Color = Color.Yellow;
            Chart1.Series["Series1"].Points[2].IsValueShownAsLabel = true;
            Chart1.Series["Series1"].Points[3].Color = Color.RosyBrown;
            Chart1.Series["Series1"].Points[3].IsValueShownAsLabel = true;
            Chart1.Series["Series1"].Points[4].Color = Color.Green;
            Chart1.Series["Series1"].Points[4].IsValueShownAsLabel = true;
            
            Chart1.Series["Series1"].Points[0].MapAreaAttributes = 
              "onmouseover=\"showTooltip(#VALX,#VALY,event);\"";
            Chart1.Series["Series1"].Points[1].MapAreaAttributes = 
              "onmouseover=\"showTooltip(#VALX,#VALY,event);\"";
            Chart1.Series["Series1"].Points[2].MapAreaAttributes = 
              "onmouseover=\"showTooltip(#VALX,#VALY,event);\"";
            Chart1.Series["Series1"].Points[3].MapAreaAttributes = 
              "onmouseover=\"showTooltip(#VALX,#VALY,event);\"";
            Chart1.Series["Series1"].Points[4].MapAreaAttributes = 
              "onmouseover=\"showTooltip(#VALX,#VALY,event);\"";
            Chart1.Attributes.Add("onmouseover","return hide()");
        }
        protected void PDlink_Click(object sender, EventArgs e)
        {
            Response.Redirect("Redirected.aspx");
        }
    }
}

Don't forget to include all the namespaces as above. I have used onmouseover event on the points of the chart dynamically created for displaying the tool tip div and onmouseover event on the chart itself to hide the tool tip div. The tool tip thus created will have the x axis, y axis values of the chart displayed in it along with a link which redirects to another page (can be used for showing details of particular data). 

Points of Interest 

The onmouseover and onmouseout events are usually used for displaying and hiding something (here the tool tip div).... but only one among both the events are being fired by the map area attributes that I have used.. so we can either hide the div or display it.. so i thought of replacing the onmouseout of the point with onmouseover of the chart Smile ...... Just try this stuff.....Its pretty interesting for beginners I suppose.... Cheers Smile....

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) Aspire Systems
India India
Just Started Software development( kind of a kiddo for most software giants here)... Exploring a lot in .NET technology..Want to be a future geek.. so here Smile | :)

Comments and Discussions

 
QuestionAdding $ symbol for pie chart series value Pin
bhuvana.k10-May-13 0:27
bhuvana.k10-May-13 0:27 
AnswerRe: Adding $ symbol for pie chart series value Pin
K C R10-May-13 5:12
K C R10-May-13 5:12 
QuestionNeed clarification.... Pin
Rashmi0920-Jan-13 17:40
Rashmi0920-Jan-13 17:40 
AnswerRe: Need clarification.... Pin
K C R12-May-13 4:18
K C R12-May-13 4:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.