Introduction
The best way to introlduce some information to some is using chart. ASP.NET have a chart control but it not the best about performance. Chart.js is a good ideal.
Background
- Working with MS SQL Database
- Javascript
- Web form
Using the code
1. Download Chart.js
You can get Chart.js from this addess: https://github.com/chartjs/Chart.js/releases
2. Create new ASP.NET project with Visual Studio and copy Chart.js was download in previous step to root project
3. Create new Web form with name "Home.aspx" and add some code lines like this
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="VisualData.Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="ChartJS.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="ltChart" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
4. Open Web.config file to add new connection string to connect to your MS SQL Server database
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="myConnection" connectionString="Data Source=.\mySQLInstance; initial catalog=myDatabaseName; user id=myUsername; password=myPassword;"/>
</connectionStrings>
</configuration>
5. Switch to code view and start write some code
private void ShowData()
{
String myConnection = ConfigurationManager.ConnectionStrings["myConnection"].ToString();
SqlConnection con = new SqlConnection(myConnection);
String query = "Select top 100 AirTemperature From tbWeathers Where stationID=1 order by id desc";
SqlCommand cmd = new SqlCommand(query, con);
DataTable tb = new DataTable();
try
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
tb.Load(dr, LoadOption.OverwriteChanges);
con.Close();
}
catch { }
if(tb != null)
{
String chart = "";
chart = "<canvas id=\"line-chart\" width=\"100%\" height=\"40\"></canvas>";
chart += "<script>";
chart += "new Chart(document.getElementById(\"line-chart\"), { type: 'line', data: {labels: [";
for (int i = 0; i < 100; i++)
chart += i.ToString() + ",";
chart = chart.Substring(0, chart.Length - 1);
chart += "],datasets: [{ data: [";
String value = "";
for (int i = 0; i < tb.Rows.Count; i++)
value += tb.Rows[i]["NhietDo"].ToString() + ",";
value = value.Substring(0, value.Length - 1);
chart += value;
chart += "],label: \"Air Temperature\",borderColor: \"#3e95cd\",fill: true}";
chart += "]},options: { title: { display: true,text: 'Air Temperature (oC)'} }";
chart += "});";
chart += "</script>";
ltChart.Text = chart;
}
}
6. Build project and run to show your result
Points of Interest
Now you can display your data in the better way than the table.