Highcharts Asp.net: Create Pie chart with jQuery ajax in C# (MS SQL database)

/ / 14 Comments

HighCharts Pie Chart: This article explains how to create a dynamic pie chart using Highcharts in Asp.net C#. Pie chart data will be generated from our database (MS SQL server) connection by calling Webmethod .i.e jQuery ajax call which gives JSON data. You can also check some of my previous charting tutorials. Now in this post, we create a pie chart using Highcharts.js library and bind data from the database.

Why Highcharts?

Highcharts create interactive charts easily for your web projects. Highcharts is the simplest yet most flexible charting API on the market. It is compatible with all modern mobile and desktop browsers including the iPhone/iPad and Internet Explorer from version 6. Pure javascript, i.e., It is solely based on native browser technologies and doesn't require client side plugins like Flash or Java.

Screenshots:




Steps to use Highcharts in Asp.net Application.

  1. Create database .i.e table with some data.
  2. Download Highcharts.js and jQuery latest library.
  3. Html Markup: add div tag where pie chart gets displayed.
  4. C#- Create a WebService (WebMethod) which returns data.
  5. jQuery – code to initialize highcharts and binding data (jQuery ajax [json data series]).

Below have provided highcharts examples .i.e working copy of highcharts Asp.net demo downloadable.


# Create Database:

Here are going to create pie chart dynamically, which displays population percentage for respected cities from our database ( MS SQL server ).

In our database, we have a Table named as `tb_city_population`, and column as `City` Name and `Population` have a look at table schema at Fig 1 and then add some data to our table as shown in Fig 2.

So we use these data to generate pie chart dynamically with highcharts plugin.

Fig 1 -




Fig 2-


Now we are down with our database base. Let's head toward Highcharts, jQuery library.


# Download Highcharts.js and jQuery latest library:

For using Highcharts in our project web application, first, we have to download highcharts and add reference of the JavaScript on our Web page or master page.

Also, add the latest jQuery library file in our web page. You can host the jQuery file on your server, or you can also use from the Google-hosted site (recommended, performance wise).

So now our head tag looks like as written below.

//*
<script src="latestJs_1.11/jquery.min.js"></script>
<script src="Highcharts/highcharts.js"></script>
//*

 


#HTML Markup :

Here we add a drop-down list as we want to show pie chart for selected year from this dropdown selected value, a div tag, and a button.

On Button tag we bind a jQuery click event which makes a jQuery ajax call and response on success Bind JSON data to Highcharts, Div tag is used to display Pie Chart.

Finally, this is how our HTML looks like as written below:

 //*
<h4>Display pie chart using Highcharts in Asp.net C#</h4>
<select id="ddlyear">
    <option>2010</option>
    <option>2011</option>
    <option>2012</option>
    <option>2013</option>
    <option>2014</option>
    <option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
    <div id="container" style="width: 500px; height: 500px"></div>
</div>
//*

# C#: Create a WebMethod, which returns JSON data, which uses to create Pie Chart dynamically.

Look :

Now we add a Web Service (ASMX file) in our Asp.net application. Then write a WebMethod, which returns JSON format data.

I must suggest you to have a look at simple jQuery ajax JSON example in Asp.net with SQL database.

In our ASMX file will create a class named as cityPopulation as shown below.

 //*
public class cityPopulation 
{
   public string city_name { get; set; }
   public int population { get; set; }
   public string id { get; set; }
}
//*

Below written Webmethod returns the list of city name with city population count, and on the client, we bind this data to our div using Highcharts to generate Pie Chart.

 //*
[WebMethod]
 public List<cityPopulation> getCityPopulation(List<string> pData)
 {
    List<cityPopulation> p = new List<cityPopulation>();
 
   using (SqlConnection cn = new SqlConnection(conn))
   {
     string myQuery = "SELECT id_, city_name, population FROM  tb_city_population WHERE  year_of = @year";
      SqlCommand cmd = new SqlCommand();
      cmd.CommandText = myQuery;
      cmd.CommandType = CommandType.Text;
      cmd.Parameters.AddWithValue("@year", pData[0]);
      cmd.Connection = cn;
      cn.Open();
      SqlDataReader dr = cmd.ExecuteReader();
     if (dr.HasRows)
     {                
         while (dr.Read())
         {
          cityPopulation cpData = new cityPopulation();
          cpData.city_name = dr["city_name"].ToString();
          cpData.population =Convert.ToInt32(dr["population"].ToString());
          p.Add(cpData);
         }
     }
   }
     return p;
 }
//*

Here this method returns variable p  having list object on cityPopulation class.


 # Jquery: code to initialize Highcharts and call jQuery ajax which display Pie Chart.

Look:

We are done with our database and server-side code, and now it's time play with jQuery at client-side.

Using jQuery will call an ajax method and on its success response we bind JSON data which generate highcharts JSON series. So our pie chart gets created with dynamic data.

Code to initialize Highcharts:

We create a new function as `drawPieChart()` which initialize Highcharts, and will call this function on our jQuery Ajax success method.

 //*
function drawPieChart(seriesData) {

    $('#container').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: 'Population percentage city wise'
        },
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {
                        color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                    }
                }
            }
        },
        series: [{
            name: "Brands",
            colorByPoint: true,
            data: seriesData
        }]
    });
}
//*

# Calling jQuery Ajax:

Here on button click, we are making an ajax call, and on its success will use `JSON` data to set highcharts series property.

 //*
$("#btnCreatePieChart").on('click', function (e) {
    var pData = [];
    pData[0] = $("#ddlyear").val();

    var jsonData = JSON.stringify({ pData: pData });

    $.ajax({
        type: "POST",
        url: "WebService.asmx/getCityPopulation",
        data: jsonData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess_,
        error: OnErrorCall_
    });

    function OnSuccess_(response) {
        var aData = response.d;
        var arr = []

        $.map(aData, function (item, index) {
            var i = [item.city_name, item.population];
            var obj = {};
            obj.name = item.city_name;
            obj.y = item.population;
            arr.push(obj);
        });
        var myJsonString = JSON.stringify(arr);
        var jsonArray = JSON.parse(JSON.stringify(arr));

        drawPieChart(jsonArray);

    }
    function OnErrorCall_(response) {
        alert("Whoops something went wrong!");
    }
    e.preventDefault();
});
//*

If you want to increase highcharts pie chart size, you can do by using the full height of the pie chart. By setting the size attribute in the plotOptions of pie and removing margins, spacing and titles from the chart. Code to set highcharts pie chart size as 100%

 //*
plotOptions: {
        pie: {
            size:'100%',
            dataLabels: {
                enabled: false
            }
    }
//*

   Output: We are done, this is how our pie chart looks

Highcharts Aspnet C# generate pie chart dynamically with database

 

Conclusion : Highcharts is an excellent plugin, easy to integrate and it also allows to add interactive charts to our web application.

In this article, we done with simple pie chart highcharts tutorial, and we can also create different kinds of charts like column, bar, line, area, etc.

Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below!

 

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

14 Comments