Show Doughnut chart on GridView cell Mouseover in ASP.Net

Last Reply one year ago By dharmendr

Posted one year ago

i m showing task Avg point, Project AvgPoint and Lab Avg point in gridview.

on mouse over of Avg point wnat to task total alloted task,completed task,rejected and uncompleted task in graph

trying to using Admin LTE Donut chart

sample record like

total tasks 10

completed tasks 4        and Avg of completeD Tasks is 80%

rejected tasks 1

uncompleted tasks 2

Running Tasks 3

Posted one year ago Modified on one year ago

Hi mukesh1,

Using the below article i have created the example.

Implement Free HTML5 Canvas charts using Chart.js in ASP.Net

Check this example. Now please take its reference and change as per your database structure.

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/excanvas/r3/excanvas.js" type="text/javascript"></script>
<script src="//cdn.jsdelivr.net/chart.js/0.2/Chart.js" type="text/javascript"></script>
<form id="form1" runat="server">
<script type="text/javascript">
    $(function () {
        $('[id*=gvOrders] tr:has(td)').each(function () {
            $(this).find('td').eq(2).mouseover(function () {
                var country = $(this).html();
                LoadChart(country);
                $('#dvChartContent').attr('style', 'display: block;');

            }).mouseout(function () {
                $('#dvChartContent').attr('style', 'display: none;');
            });
        });
    });
    function LoadChart(country) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetChart",
            data: "{country: '" + country + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                $("#dvChart").html("");
                $("#dvLegend").html("");
                var data = eval(r.d);
                var el = document.createElement('canvas');
                $("#dvChart")[0].appendChild(el);

                //Fix for IE 8
                if ($.browser.msie && $.browser.version == "8.0") {
                    G_vmlCanvasManager.initElement(el);
                }
                var ctx = el.getContext('2d');
                var userStrengthsChart;
                userStrengthsChart = new Chart(ctx).Doughnut(data);
                for (var i = 0; i < data.length; i++) {
                    var div = $("<div />");
                    div.css("margin-bottom", "10px");
                    div.html("<span style = 'display:inline-block;height:10px;width:10px;background-color:" + data[i].color + "'></span> " + data[i].text);
                    $("#dvLegend").append(div);
                }
            },
            failure: function (response) {
                alert('There was an error.');
            }
        });
    }
</script>
<asp:GridView runat="server" ID="gvOrders" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="Id" />
        <asp:BoundField DataField="ShipCity" HeaderText="City" />
        <asp:BoundField DataField="ShipCountry" HeaderText="Country" />
    </Columns>
</asp:GridView>
<div id="dvChartContent" style="display: none;">
    <div id="dvChart" style="float: left">
    </div>
    <div id="dvLegend" style="float: left">
    </div>
</div>
<style type="text/css">
    #dvChartContent
    {
        position: absolute;
        display: inline-block;
        background-color: #FB66AA;
        width: 400px;
        z-index: 1;
        top: 8px;
        left: 230px;
    }
</style>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.Services;

VB.Net

Imports System.Data
Imports System.Text
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Configuration

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        string query = "SELECT TOP 4 CustomerID,ShipCity,ShipCountry FROM Orders";
        SqlCommand cmd = new SqlCommand(query);
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    gvOrders.DataSource = dt;
                    gvOrders.DataBind();
                }
            }
        }
    }
}

[WebMethod]
public static string GetChart(string country)
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country);
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = query;
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("[");
                while (sdr.Read())
                {
                    sb.Append("{");
                    System.Threading.Thread.Sleep(50);
                    string color = String.Format("#{0:X6}", new Random().Next(0x1000000));
                    sb.Append(string.Format("text :'{0}', value:{1}, color: '{2}'", sdr[0], sdr[1], color));
                    sb.Append("},");
                }
                sb = sb.Remove(sb.Length - 1, 1);
                sb.Append("]");
                con.Close();
                return sb.ToString();
            }
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim conString As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
        Dim query As String = "SELECT TOP 4 CustomerID,ShipCity,ShipCountry FROM Orders"
        Dim cmd As SqlCommand = New SqlCommand(query)
        Using con As SqlConnection = New SqlConnection(conString)
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using dt As DataTable = New DataTable()
                    sda.Fill(dt)
                    gvOrders.DataSource = dt
                    gvOrders.DataBind()
                End Using
            End Using
        End Using
    End If
End Sub

<WebMethod()> _
Public Shared Function GetChart(country As String) As String
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
    Using con As New SqlConnection(constr)
        Dim query As String = String.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", country)
        Using cmd As New SqlCommand()
            cmd.CommandText = query
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                Dim sb As New StringBuilder()
                sb.Append("[")
                While sdr.Read()
                    sb.Append("{")
                    System.Threading.Thread.Sleep(50)
                    Dim color As String = [String].Format("#{0:X6}", New Random().Next(&H1000000))
                    sb.Append(String.Format("text :'{0}', value:{1}, color: '{2}'", sdr(0), sdr(1), color))
                    sb.Append("},")
                End While
                sb = sb.Remove(sb.Length - 1, 1)
                sb.Append("]")
                con.Close()
                Return sb.ToString()
            End Using
        End Using
    End Using
End Function

Screenshot