Hi dharmendr sir,
I have codde of gantt chart. it has no error but also not making bars. please sir help me. my data base structure is like this.
My database table structure is like this.
Id int
Months nvarchar(50)
Starttime nvarchar(50)
Endtime nvarchar(50)
My database table is saving value like this,
Months starttime endtime
Jan 10:00 10:10
Feb 12:00 12:15
Mar 9:00 9:10
And so on
HTML
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="WebApplication1.WebForm4" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></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: "WebForm4.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) {
const validChartData = chartData.filter(item => item.x && item.y);
const processedChartData = validChartData.map(item => ({
label: item.y,
data: [{
x: item.x[0], // Start time
y: uniqueMonths.indexOf(item.y), // Month index as y-value
base: item.x[0], // Start time
end: item.x[1], // End time
}],
}));
const config = {
type: 'bar',
data: {
datasets: processedChartData,
},
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,
},
},
},
};
// 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>
Code
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.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm4 : 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[] { dt.Rows[i]["starttime"].ToString(), dt.Rows[i]["endtime"].ToString() },
y = dt.Rows[i]["months"]
});
}
return chartData;
}
}
}
}
}
}