How To Implement Google Pie Chart Dynamically Using Entity Framework In ASP.NET

Introduction

In this article. I will demonstrate how to implement Google Pie Chart dynamically using Entity Framework in ASP.NET. I will use jQuery AJAX to retrieve the data from database and display in Google Pie Chart. The chart will display the respective data on its point line with animation.

Step 1

Open SQL Server 2014 and create a database table to insert and retrieve the data.

  1. CREATE TABLE [dbo].[CompanyAnnualReport](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [DepartmentName] [nvarchar](50) NULL,  
  4.     [EmployeeHired] [intNULL,  
  5.  CONSTRAINT [PK_CompanyAnnualReport] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [ID] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
  10.   
  11. GO  
ASP.NET

Step 2

Open Visual Studio 2015 >> New Project and create an empty web application project.

Screenshot for creating new project 1

After clicking on New Project, one window will appear. Select Web from the left panel, choose ASP.NET Web Application, give a meaningful name to your project and then click on OK.

Screenshot for creating new project 2

After clicking on OK, one more window will appear. Choose Empty >> check on Web Forms checkbox and click on OK.

Screenshot for creating new project  3

Step 3

Click on Tools >> select NuGet Package Manager. Then, choose Manage NuGet Packages for Solution and click on it.

Screenshot for NuGet Package

After that, a window will appear. Choose Browse type bootstrap and install the package in the project.

Similarly, type jQuery and install the latest version of jQuery package in the project from NuGet; then close NuGet Solution.

Keep the useful files in Content and Scripts folder, as shown below.

 Step 4

To add Entity Framework, right-click on Models folder, select Add, then select New Item, then click on it

After clicking on the New item, you will get a windo. From there select Data from the left panel and choose ADO.NET Entity Data Model, give it a name DBModels (This name is not mandatory. You can give any name); then click on Add.

After you click on Add, a window wizard will open. Choose EF Designer from the database and click Next.

 
In the next window, choose New Connection.

Another window will appear to add your server name. If it is local, then enter dot (.). Choose your database and click on OK.

The connection will get added. If you wish, save it as default connect as you want. You can change the name of your connection below. It will save connection in web config. Click on Next.

After clicking on NEXT, another window will appear. Choose database table name as shown below screenshot, then click on Finish. Entity Framework will be added to the respective class generated under Models folder.


The following class will be added.

  1. namespace PieChart_Demo.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class CompanyAnnualReport  
  7.     {  
  8.         public int ID { get; set; }  
  9.         public string DepartmentName { get; set; }  
  10.         public Nullable<int> EmployeeHired { get; set; }  
  11.     }  
  12. }  

Step 5

Right-click on project, select Add >> Web Form and click on it.

After clicking on the web form, one window will appear. Give it a meaningful name and click on OK.

Step 6

Right-click on scripts folder, select Add >> JavaScript File then click on it.

After clicking on JavaScript File window will appear. Give it the name PieChart then click on OK.

Add the following jQuery and JavaScript code to retrieve the data from database and display in chart.

  1. var chartData; // global variable for hold chart data  
  2. google.load("visualization""1", { packages: ["corechart"] });  
  3. // Here We will fill chartData  
  4. $(document).ready(function () {  
  5.     $.ajax({  
  6.         url: "PieChart.aspx/GetChartData",  
  7.         data: "",  
  8.         dataType: "json",  
  9.         type: "POST",  
  10.         contentType: "application/json; chartset=utf-8",  
  11.         success: function (data) {  
  12.             chartData = data.d;  
  13.         },  
  14.         error: function () {  
  15.             alert("Error loading data! Please try again.");  
  16.         }  
  17.     }).done(function () {  
  18.         // after complete loading data  
  19.         google.setOnLoadCallback(drawChart);  
  20.         drawChart();  
  21.     });  
  22. });  
  23. function drawChart() {  
  24.     var data = google.visualization.arrayToDataTable(chartData);  
  25.   
  26.     var options = {  
  27.         title: "Company Annual Report",  
  28.         pointSize: 5  
  29.     };  
  30.     var pieChart = new google.visualization.PieChart(document.getElementById('chart_div'));  
  31.     pieChart.draw(data, options);  
  32.   
  33. }  

Step 7

Add the following scripts and styles in head section of web form.

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2. <script type="text/javascript" src="https://www.google.com/jsapi"></script>  
  3.  <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  4. <script src="scripts/jquery-3.3.1.min.js"></script>  
  5.  <script src="scripts/bootstrap.min.js"></script>  
  6.  <script src="scripts/PieChart.js"></script>  

Step 8

Design web form using textbox control, button control, and gridview control and bootstrap 4 class to look good.

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.         <div class="container py-4">  
  4.             <h5 class="text-center text-uppercase">How to Implement Google Pie Chart Dynamically Using Entity Framework in Asp.Net</h5>  
  5.             <div class="card">  
  6.                 <div class="card-header bg-primary text-white text-uppercase">  
  7.                     <h6 class="card-title">Company Annual Hiring Report</h6>  
  8.                 </div>  
  9.                 <div class="card-body">  
  10.                     <button style="margin-bottom: 10px;" type="button" class="btn btn-primary rounded-0" data-toggle="modal" data-target="#pieChart">  
  11.                         <i class="fa fa-plus-circle"></i>Add New Report  
  12.                     </button>  
  13.                     <div class="modal" id="pieChart">  
  14.                         <div class="modal-dialog modal-lg">  
  15.                             <div class="modal-content">  
  16.                                 <div class="modal-header">  
  17.                                     <h4 class="modal-title">Company Annual Report</h4>  
  18.                                     <button type="button" class="close" data-dismiss="modal">×</button>  
  19.                                 </div>  
  20.                                 <div class="modal-body">  
  21.                                     <div class="row">  
  22.                                         <div class="col-md-6">  
  23.                                             <div class="form-group">  
  24.                                                 <label>Department Name:</label>  
  25.                                                 <asp:TextBox ID="txtDepartmentName" CssClass="form-control" runat="server"></asp:TextBox>  
  26.                                                 <asp:RequiredFieldValidator ID="rfvDeptName" ControlToValidate="txtDepartmentName" CssClass="text-danger" runat="server" ErrorMessage="Please enter department name"></asp:RequiredFieldValidator>  
  27.                                             </div>  
  28.                                         </div>  
  29.                                         <div class="col-md-6">  
  30.                                             <div class="form-group">  
  31.                                                 <label>Number of emplyee hired:</label>  
  32.                                                 <asp:TextBox ID="txtEmployeeHired" CssClass="form-control" runat="server"></asp:TextBox>  
  33.                                                 <asp:RequiredFieldValidator ID="rfvHired" ControlToValidate="txtEmployeeHired" CssClass="text-danger" runat="server" ErrorMessage="Please enter number of employee hired"></asp:RequiredFieldValidator>  
  34.                                             </div>  
  35.                                         </div>  
  36.                                     </div>  
  37.                                 </div>  
  38.                                 <div class="modal-footer">  
  39.                                     <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>  
  40.                                     <asp:Button ID="btnSubmit" CssClass="btn btn-primary rounded-0" runat="server" Text="Submit" OnClick="btnSubmit_Click" />  
  41.                                 </div>  
  42.                             </div>  
  43.                         </div>  
  44.                     </div>  
  45.                     <asp:GridView ID="CompanyAnnualReportGridView" AutoGenerateColumns="false" CssClass="table table-bordered table-striped" runat="server">  
  46.                         <Columns>  
  47.                             <asp:BoundField HeaderText="ID" DataField="ID" />  
  48.                             <asp:BoundField HeaderText="Department Name" DataField="DepartmentName" />  
  49.                             <asp:BoundField HeaderText="Employee Hired" DataField="EmployeeHired" />  
  50.                         </Columns>  
  51.                     </asp:GridView>  
  52.                 </div>  
  53.             </div>  
  54.   
  55.             <div id="chart_div" style="width: 100%; height: 400px">  
  56.             </div>  
  57.         </div>  
  58.     </form>  
  59. </body>  

Step 9

Double click on submit button and write following c# code.

Add following namespace

  1. using PieChart_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web.Script.Services;  
  6. using System.Web.Services;  
  7. using System.Web.UI.WebControls;  

Complete C# code of web form

  1. using PieChart_Demo.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web.Script.Services;  
  6. using System.Web.Services;  
  7. using System.Web.UI.WebControls;  
  8.   
  9. namespace PieChart_Demo  
  10. {  
  11.     public partial class PieChart : System.Web.UI.Page  
  12.     {  
  13.         protected void Page_Load(object sender, EventArgs e)  
  14.         {  
  15.             if (!IsPostBack)  
  16.             {  
  17.                 BindGridView();  
  18.                 ClearTextBox();  
  19.             }  
  20.         }  
  21.         private void ClearTextBox()  
  22.         {  
  23.             txtDepartmentName.Text = string.Empty;  
  24.             txtEmployeeHired.Text = string.Empty;  
  25.         }  
  26.         private void BindGridView()  
  27.         {  
  28.             using (DBModel db = new DBModel())  
  29.             {  
  30.                 CompanyAnnualReportGridView.DataSource = (from r in db.CompanyAnnualReports select r).ToList();  
  31.                 CompanyAnnualReportGridView.DataBind();  
  32.             }  
  33.         }  
  34.   
  35.         [WebMethod]  
  36.         [ScriptMethod(ResponseFormat = ResponseFormat.Json)]  
  37.         public static object[] GetChartData()  
  38.         {  
  39.             List<CompanyAnnualReport> data = new List<CompanyAnnualReport>();  
  40.             //Here MyDatabaseEntities  is our dbContext  
  41.             using (DBModel db = new DBModel())  
  42.             {  
  43.                 data =db.CompanyAnnualReports.ToList();  
  44.             }  
  45.             var chartData = new object[data.Count + 1];  
  46.             chartData[0] = new object[]{  
  47.                     "Department Name",  
  48.                     "Employee Hired"  
  49.                 };  
  50.             int j = 0;  
  51.             foreach (var i in data)  
  52.             {  
  53.                 j++;  
  54.                 chartData[j] = new object[] { i.DepartmentName, i.EmployeeHired};  
  55.             }  
  56.   
  57.             return chartData;  
  58.         }  
  59.   
  60.         protected void btnSubmit_Click(object sender, EventArgs e)  
  61.         {  
  62.             using (DBModel db = new DBModel())  
  63.             {  
  64.                 CompanyAnnualReport companyreport = new CompanyAnnualReport();  
  65.                 companyreport.DepartmentName = txtDepartmentName.Text;  
  66.                 companyreport.EmployeeHired = Convert.ToInt32(txtEmployeeHired.Text);  
  67.                 db.CompanyAnnualReports.Add(companyreport);  
  68.                 db.SaveChanges();  
  69.                 ClearTextBox();  
  70.             }  
  71.             this.BindGridView();  
  72.         }  
  73.     }  
  74. }  

Step 9

Right click on web config file add the following code to avoid validation related error.

  1. <appSettings>  
  2.   <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />  
  3. </appSettings> 

Step 10

Run project ctrl+F5

Screenshot 1

Screenshot 2

Conclusion

In this article, I have explained how to implement Google Pie Chart dynamically using Entity Framework in ASP.NET. We can add a yearly report of department name and number of employees hired in a year by clicking on Add New Report button.  I hope it will be useful in your upcoming projects.


Similar Articles