Introduction
In this article, I will demonstrate how to implement Google Bar Chart dynamically using entity framework in ASP.NET. I will use jQuery Ajax to retrieve data from the database and display it in Google Bar Chart. The chart will display respective data on its point line with animations.
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 to give a meaningful name to 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 on 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 click on it.
Screenshot for NuGet Package
After that, a window will appear, choose Browse type bootstrap, and install a 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) than click on Add.
Screenshot for adding entity framework 2
After you click on add a window wizard will open choose EF Designer from database and click Next.
Screenshot for adding entity framework 3
After clicking on next a window will appear. Choose New Connection.
Screenshot for adding entity framework 4
Another window will appear 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
A connection will be added. 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 choose database table name as shown in the below screenshot then click 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 GoogleBarChart_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 meaningful name and click on OK
Step 6
Right click on scripts folder, select Add, choose JavaScript File then click on it.
After clicking on JavaScript File a window will appear, give it the name BarChart then click on OK.
Add fthe ollowing jQuery and JavaScript code to retrieve data from the database and display it in chart.
- var chartData;
- google.load("visualization", "1", { packages: ["corechart"] });
-
- $(document).ready(function () {
- $.ajax({
- url: "BarChart.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 Hiring Report",
- pointSize: 5
- };
- var barChart = new google.visualization.BarChart(document.getElementById('Barchart_div'));
- barChart.draw(data, options);
- }
Step 7
Add the following scripts and styles in the head section of the 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/BarChart.js"></script>
Step 8
Design the 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 Bar 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>Year 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="Barchart_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 GoogleBarChart_Demo.Models;
- using System.Web.Script.Services;
- using System.Web.Services;
Complete C# code of web form
- using GoogleBarChart_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 GoogleBarChart_Demo
- {
- public partial class BarChart : 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 company = new CompanyHiringReport();
- company.Year = Convert.ToInt32(txtYear.Text);
- company.Account = Convert.ToInt32(txtAccountDepartment.Text);
- company.HR = Convert.ToInt32(txtHRDepartment.Text);
- company.IT = Convert.ToInt32(txtITDepartment.Text);
- company.Sales = Convert.ToInt32(txtSalesDepartment.Text);
- company.Marketing = Convert.ToInt32(txtMarketingDepartment.Text);
-
- db.CompanyHiringReports.Add(company);
- db.SaveChanges();
- ClearTextBox();
- }
- this.BindGridView();
- }
- }
- }
Step 9
Right click on web config file, add the following code to avoid validation related error.
- <appSettings>
- <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
- </appSettings>
Step 10
Run project ctrl+F5
Screenshot 1
Screenshot 2
Conclusion
In this article, I have explained how to implement Google Bar Chart dynamically using entity framework in ASP.NET. We can add a yearly report by department name and number of the employee hired by year by clicking on the Add a New Report button.