Hi dharmendr sir,
I write a code of gantt chart populated from data base. it make x axis and y axis accordingly but not making bars of graph. please help me sir.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="mytest.aspx.cs" Inherits="WebApplication1.mytest" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Chart JS with w ww.chartjs3.com</title>
<style>
* {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.chartMenu {
width: 100vw;
height: 40px;
background: #1A1A1A;
color: rgba(54, 162, 235, 1);
}
.chartMenu p {
padding: 10px;
font-size: 20px;
}
.chartCard {
width: 100vw;
height: calc(100vh - 40px);
background: rgba(54, 162, 235, 0.2);
display: flex;
align-items: center;
justify-content: center;
}
.chartBox {
width: 700px;
padding: 20px;
border-radius: 20px;
border: solid 3px rgba(54, 162, 235, 1);
background: white;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="chartMenu">
<p>WWW.CHARTJS3.COM (Chart JS <span id="chartVersion"></span>)</p>
</div>
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function () {
// Fetch data from the server when the page loads
fetchDataFromServer();
});
function fetchDataFromServer() {
$.ajax({
type: "POST",
url: "mytest.aspx/GetChartData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log("Data from server:", data);
// Parse date and time strings to JavaScript Date objects
data.d.forEach(function (item) {
item.starttime = parseTimeString(item.x[0]);
item.endtime = parseTimeString(item.x[1]);
});
// Get unique month names from the data
const uniqueMonths = [...new Set(data.d.map(item => item.y))];
// Call a function to update the Gantt chart with the retrieved data and month names
updateGanttChart(data.d, uniqueMonths);
},
error: function (error) {
console.log("Error fetching data from server:", error);
}
});
}
function parseTimeString(timeString) {
// Check if timeString is in /Date(...) format
const dateRegex = /^\/Date\((\d+)([+-]\d{4})?\)\/$/;
const match = timeString.match(dateRegex);
if (match) {
// Convert /Date(...) to milliseconds
const milliseconds = parseInt(match[1]);
return new Date(milliseconds);
} else if (timeString) {
// Parse time string in HH:mm format and create a new Date object
const [hours, minutes] = timeString.split(':').map(Number);
const date = new Date();
date.setHours(hours, minutes, 0, 0);
return date;
} else {
return null; // Return null or handle the case as needed
}
}
function updateGanttChart(chartData, uniqueMonths) {
// Filter out items with null starttime and endtime
const validChartData = chartData.filter(item => item.starttime && item.endtime);
// Prepare Gantt chart data
const ganttData = validChartData.map(item => ({
label: item.y,
data: [{
x: item.starttime,
y: uniqueMonths.indexOf(item.y), // Use the index of the month as the y-value
base: item.starttime,
end: item.endtime,
}],
}));
const config = {
type: 'bar',
data: {
datasets: ganttData,
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'minute',
displayFormats: {
minute: 'HH:mm',
},
},
title: {
display: true,
text: 'Time',
},
},
y: {
type: 'category',
title: {
display: true,
text: 'Months',
},
labels: uniqueMonths, // Set y-axis labels to unique months
},
},
},
};
// Render the Gantt chart
const ganttChart = new Chart(
document.getElementById('myChart'),
config
);
// Instantly assign Chart.js version
const chartVersion = document.getElementById('chartVersion');
chartVersion.innerText = Chart.version;
}
</script>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class mytest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<object> GetChartData()
{
string conString = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
string query = "SELECT * FROM test";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
List<object> chartData = new List<object>();
for (int i = 0; i < dt.Rows.Count; i++)
{
chartData.Add(new
{
x = new[] { Convert.ToDateTime(dt.Rows[i]["starttime"]), Convert.ToDateTime(dt.Rows[i]["endtime"]) },
y = dt.Rows[i]["months"]
});
}
return chartData;
}
}
}
}
}
}