Introduction
In this article, I will demonstrate how to implement a Google combo chart dynamically using entity framework in ASP.NET. I will use jQuery Ajax to retrieve data from database and display in Google Combo Chart. The Chart will display respective data on its point line with animation.
Step 1
Open SQL server 2014 and create a database table to insert data and retrieve data.
- CREATE TABLE [dbo].[CompanyHiringReport](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [Year] [int] NULL,
- [Account] [int] NULL,
- [HR] [int] NULL,
- [IT] [int] NULL,
- [Sales] [int] NULL,
- [Marketing] [int] NULL,
- CONSTRAINT [PK_CompanyHiringReport] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
Step 2
Open Visual Studio 2015 click on 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 left panel, choose ASP.NET Web Application and give a meaningful name of your project then click on OK as shown in the below screenshot.
Screenshot for creating new project 2
After clicking on OK one more window will appear, choose empty, check the Web Forms checkbox, and click on OK, as shown in the below screenshot.
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 as bootstrap, and install the package in the project as shown.
Similarly, type JQuery and install the latest version of JQuery package in the project from NuGet then close NuGet Solution.
Keep the useful file in Content and scripts folder as shown below.
Step 4
Add entity framework, right click on Models folder, select Add, then select New Item then click on it.
Screenshot for adding entity framework 1
After clicking on the New item you will get a window, from there select Data from the left panel and choose ADO.NET Entity Data Model, name it DBModels (this name is not mandatory you can give any name) then click on Add.
Screenshot for adding entity framework 2
After you click on Add, a window wizard will open, choose EF Designer from the database and click Next.
Screenshot for adding entity framework 3
After click on Next a window will appear. Choose New Connection
Screenshot for adding entity framework 4
Another window will appear asking you to add your server name; if it is local then enter a dot (.). Choose your database and click on OK.
Screenshot for adding entity framework 5
The connection will get added. If you wish to save connect as you want. You can change the name of your connection below. It will save connection in web config then click on Next.
Screenshot for adding entity framework 6
After clicking on NEXT another window will appear to choose database table name as shown in below screenshot then click on Finish. Entity framework will be added and respective class gets generated under Models folder.
Screenshot for adding entity framework 7
Screenshot for adding entity framework 8
Following class will be added
- namespace GoogleComboChart_Demo.Models
- {
- using System;
- using System.Collections.Generic;
-
- public partial class CompanyHiringReport
- {
- public int ID { get; set; }
- public Nullable<int> Year { get; set; }
- public Nullable<int> Account { get; set; }
- public Nullable<int> HR { get; set; }
- public Nullable<int> IT { get; set; }
- public Nullable<int> Sales { get; set; }
- public Nullable<int> Marketing { get; set; }
- }
- }
Step 5
Right click on project, select Add, choose Web Form and click on it. As shown in the below image.
After clicking on the web form one window will appear, give it a name and click on OK
Step 6
Right click on scripts folder select Add choose JavaScript File then click on it.
After click on JavaScript File window will appear, give it the name ComboChart then click on OK.
Add the following jQuery and JavaScript code to retrieve data from database and display in chart.
- var chartData;
- google.load("visualization", "1", { packages: ["corechart"] });
-
- $(document).ready(function () {
- $.ajax({
- url: "CobmoChart.aspx/GetChartData",
- data: "",
- dataType: "json",
- type: "POST",
- contentType: "application/json; chartset=utf-8",
- success: function (data) {
- chartData = data.d;
- },
- error: function () {
- alert("Error loading data! Please try again.");
- }
- }).done(function () {
-
- google.setOnLoadCallback(drawChart);
- drawChart();
- });
- });
- function drawChart() {
- var data = google.visualization.arrayToDataTable(chartData);
- var options = {
- title: "Company Performance Product Category Wise",
- pointSize: 5,
- seriesType: "bars",
- series: { 3: { type: "line" } }
- };
- var comboChart = new google.visualization.ComboChart(document.getElementById('ComboChart_div'));
- comboChart.draw(data, options);
- }
Step 7
Add following scripts and styles in head section of web form.
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <script type="text/javascript" src="https://www.google.com/jsapi"></script>
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <script src="scripts/jquery-3.3.1.min.js"></script>
- <script src="scripts/bootstrap.min.js"></script>
- <script src="scripts/ComboChart.js"></script>
Step 8
Design web form using textbox control, button control and gridview control and bootstrap 4 class to look good.
- <body>
- <form id="form1" runat="server">
- <div class="container py-4">
- <h5 class="text-center text-uppercase">How to Implement Google Combo Chart Dynamically Using Entity Framework in Asp.Net</h5>
- <div class="card">
- <div class="card-header bg-primary">
- <h6 class=" text-upparcase text-white">Company Hiring Report</h6>
- </div>
- <div class="card-body">
- <button style="margin-bottom: 10px;" class="btn btn-primary rounded-0" type="button" data-target="#CompantReport" data-toggle="modal"><i class="fa fa-plus-circle"></i>Add New Report</button>
- <div class="modal fade" id="CompantReport">
- <div class="modal-dialog modal-lg">
- <div class="modal-content">
- <div class="modal-header">
- <h4 class="modal-title">Company Hiring Report</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="row">
- <div class="col-md-4">
- <div class="form-group">
- <label>Month of hiring:</label>
- <asp:TextBox ID="txtYear" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvYear" ControlToValidate="txtYear" CssClass="text-danger" runat="server" ErrorMessage="Please enter year"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>Account Department:</label>
- <asp:TextBox ID="txtAccountDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvAccount" ControlToValidate="txtYear" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>HR Department:</label>
- <asp:TextBox ID="txtHRDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvHR" ControlToValidate="txtHRDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-md-4">
- <div class="form-group">
- <label>IT Department:</</label>
- <asp:TextBox ID="txtITDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvIT" ControlToValidate="txtITDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>Sales Department:</label>
- <asp:TextBox ID="txtSalesDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvSales" ControlToValidate="txtSalesDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <label>Marketing Department:</label>
- <asp:TextBox ID="txtMarketingDepartment" CssClass="form-control" runat="server"></asp:TextBox>
- <asp:RequiredFieldValidator ID="rfvMarketing" ControlToValidate="txtMarketingDepartment" CssClass="text-danger" runat="server" ErrorMessage="Please enter number employee hired"></asp:RequiredFieldValidator>
- </div>
- </div>
- </div>
- </div>
- <div class="modal-footer">
- <asp:Button ID="btnSubmit" CssClass="btn btn-primary rounded-0" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
- <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
- </div>
- </div>
- </div>
- </div>
- <asp:GridView ID="CompanyHiringReportGridView" AutoGenerateColumns="false" runat="server" CssClass="table table-bordered table-striped">
- <Columns>
- <asp:BoundField HeaderText="ID" DataField="ID" />
- <asp:BoundField HeaderText="Year" DataField="Year" />
- <asp:BoundField HeaderText="Account Department" DataField="Account" />
- <asp:BoundField HeaderText="HR Department" DataField="HR" />
- <asp:BoundField HeaderText="IT Department" DataField="IT" />
- <asp:BoundField HeaderText="Sales Department" DataField="Sales" />
- <asp:BoundField HeaderText="Marketing Department" DataField="Marketing" />
- </Columns>
- </asp:GridView>
- </div>
- </div>
- <div id="ComboChart_div" style="width: 100%; height: 400px">
- </div>
- </div>
- </form>
- </body>
Step 9
Double click on submit button and write the following C# code.
Add the following namespace.
- using GoogleComboChart_Demo.Models;
- using System.Web.Script.Services;
- using System.Web.Services;
Complete C# code of web form
- using GoogleComboChart_Demo.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web.Script.Services;
- using System.Web.Services;
- using System.Web.UI.WebControls;
-
- namespace GoogleComboChart_Demo
- {
- public partial class CobmoChart : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindGridView();
- ClearTextBox();
- }
- }
- private void ClearTextBox()
- {
- txtYear.Text = string.Empty;
- txtAccountDepartment.Text = string.Empty;
- txtHRDepartment.Text = string.Empty;
- txtITDepartment.Text = string.Empty;
- txtSalesDepartment.Text = string.Empty;
- txtMarketingDepartment.Text = string.Empty;
- }
-
- private void BindGridView()
- {
- using (DBModel db = new DBModel())
- {
- CompanyHiringReportGridView.DataSource = (from r in db.CompanyHiringReports select r).ToList();
- CompanyHiringReportGridView.DataBind();
- }
- }
- [WebMethod]
- [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
- public static object[] GetChartData()
- {
- List<CompanyHiringReport> data = new List<CompanyHiringReport>();
- using (DBModel db = new DBModel())
- {
- data = db.CompanyHiringReports.ToList();
- }
- var chartData = new object[data.Count + 1];
- chartData[0] = new object[]{
- "Year",
- "Accounts",
- "HR",
- "IT",
- "Sales",
- "Marketing"
- };
- int j = 0;
- foreach (var i in data)
- {
- j++;
- chartData[j] = new object[] { i.Year.ToString(), i.Account, i.HR, i.IT, i.Sales, i.Marketing };
- }
- return chartData;
- }
-
- protected void btnSubmit_Click(object sender, EventArgs e)
- {
- using (DBModel db = new DBModel())
- {
- CompanyHiringReport companyYearly = new CompanyHiringReport();
- companyYearly.Year = Convert.ToInt32(txtYear.Text);
- companyYearly.Account = Convert.ToInt32(txtAccountDepartment.Text);
- companyYearly.HR = Convert.ToInt32(txtHRDepartment.Text);
- companyYearly.IT = Convert.ToInt32(txtITDepartment.Text);
- companyYearly.Sales = Convert.ToInt32(txtSalesDepartment.Text);
- companyYearly.Marketing = Convert.ToInt32(txtMarketingDepartment.Text);
-
- db.CompanyHiringReports.Add(companyYearly);
- db.SaveChanges();
- ClearTextBox();
- }
- this.BindGridView();
- }
- }
- }
Step 10
Right click on web config file add the following code to avoid validation related error.
- <appSettings>
- <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
- </appSettings>
Step 11
Run project ctrl+F5
Screenshot 1
Screenshot 2
Conclusion
In this article. I have explained how to implement Google combo chart dynamically using entity framework in asp.net. We can add yearly report department name and number of the employee hired by year by clicking on Add New Report button.