Click here to Skip to main content
15,898,134 members
Articles / Web Development / ASP.NET
Tip/Trick

Visual Data using Chart.js in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.78/5 (6 votes)
8 Sep 2018CPOL 50.5K   14   4
Using Chart.js to visual data from MS SQL Server database on ASP.NET web form

Introduction

The best way to introduce some information to some is using chart. ASP.NET has a chart control but it is not the best about performance. Chart.js is a good ideal.

Image 1

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 downloaded in the previous step to root project
  3. Create a new Web form with name "Home.aspx" and add some code lines like this:
    ASP.NET
    <%@ 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:
    XML
    <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 writing some code:
    C#
    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 = "";
                   // You can change your chart height by modify height value
                    chart = "<canvas id=\"line-chart\" 
                    width=\"100%\" height=\"40\"></canvas>";
                    chart += "<script>";
                    chart += "new Chart(document.getElementById(\"line-chart\"), 
                              { type: 'line', data: {labels: [";
    
                    // more details in x-axis
                    for (int i = 0; i < 100; i++)
                        chart += i.ToString() + ",";
                    chart = chart.Substring(0, chart.Length - 1);
    
                    chart += "],datasets: [{ data: [";
                    
                    // put data from database to chart
                    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 color
                    chart += "]},options: { title: { display: true,text: 
                           'Air Temperature (oC)'} }"; // Chart title
                    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 a better way than the table.

This article was originally posted at https://github.com/maihaan/chartjs

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Student
Vietnam Vietnam
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionliteral refresh Pin
Member 16879815-Nov-21 0:35
Member 16879815-Nov-21 0:35 
QuestionWORKING WITH THE SAME PROJECT Pin
Member 147923624-Apr-20 5:53
Member 147923624-Apr-20 5:53 
Questionadded sample images will be greate Pin
maxoptimus7-Sep-18 0:55
maxoptimus7-Sep-18 0:55 
added sample images will be greate
AnswerRe: added sample images will be greate Pin
mai an8-Sep-18 9:24
mai an8-Sep-18 9:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.