How To Load Data On Chart In Windows Form

In C Sharp, Programming by Baqir Ali

The most amazing thing about windows form is that it allows us to create different kinds of charts for data analysis. We can create any form of charts, such as line charts, bar charts, pie charts, etc.

We can load data to charts from any lists/arrays or from a database. But today we are going to load it from a SQL Server database called POS. The data that we are going to show on charts will be the monthly orders placed in a restaurant. The demo data is given below.

Restaurant Order Table

The above table code to create will be provided in the project folder at the end of the article.

  • First, let’s create windows form project called charts.
  • Drag and drop a chart from the toolbox on the form
  • Double click on the form, a new function will be crate called Form1_Load
  • Start coding using within try and catch parenthesis
Try
{
     // code here
}
catch(Exception ex)
{
     // display errors here
}
finally
{
     //close database connection here
}
  • Create a connection string to the database and open it, place the close connection in the finally block.
SqlConnection connection;
Try
{
     connection = new SqlConnection(@"data source=(local)\SQLEXPRESS; database=POS; Integrated Security=True");
     connection.Open();
}
catch(Exception ex)
{
     // display errors here
}
finally
{
     connection.close();
}
  • Now pass the query to the database to extract data for a specific month of a year.
try
      {
           connection = new SqlConnection(@"data source=(local)\SQLEXPRESS; database=POS; Integrated Security=True");
           connection.Open();

            SqlCommand cmd = new SqlCommand("SELECT FORMAT (orders.Orderdate, 'dd-MM-yy') as [Date], sum(orders.OrderGrandTotal) as Total FROM orders where year(orders.orderdate)='2020' and datename(month,orders.orderdate)='Jully' group by orders.orderdate", connection);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dtStock = new DataTable();
            da.Fill(dtStock);


     }
     catch (Exception ex)
     {
            throw new Exception("Could not get data");
     }
     finally
     {
            connection.Close();
     }