Hi gmrneeraj,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms.DataVisualization.Charting;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Windows.Forms.DataVisualization.Charting
Code
C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string query = "SELECT TOP 10 CONVERT(VARCHAR(10),OrderDate,103) OrderDate,CAST(SUM(Freight) AS INT) Total FROM Orders GROUP BY OrderDate";
DataTable dt = GetData(query);
string[] x = (from p in dt.AsEnumerable()
select p.Field<string>("OrderDate")).ToArray();
int[] y = (from p in dt.AsEnumerable()
select p.Field<int>("Total")).ToArray();
Chart1.Series[0].ChartType = SeriesChartType.Column;
Chart1.Series[0].IsValueShownAsLabel = true;
Chart1.Series[0].Points.DataBindXY(x, y);
Chart1.Legends[0].Enabled = false;
Chart1.ChartAreas[0].AxisX.Interval = 1;
}
private static DataTable GetData(string query)
{
string constr = @"Data Source=.\SQL2014;Initial Catalog=Northwind;User ID=sa;Password=pass@123";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
VB.Net
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim query As String = "SELECT TOP 10 CONVERT(VARCHAR(10),OrderDate,103) OrderDate,CAST(SUM(Freight) AS INT) Total FROM Orders GROUP BY OrderDate"
Dim dt As DataTable = GetData(query)
Dim x As String() = (From p In dt.AsEnumerable()
Select p.Field(Of String)("OrderDate")).ToArray()
Dim y As Integer() = (From p In dt.AsEnumerable()
Select p.Field(Of Integer)("Total")).ToArray()
Chart1.Series(0).ChartType = SeriesChartType.Column
Chart1.Series(0).IsValueShownAsLabel = True
Chart1.Series(0).Points.DataBindXY(x, y)
Chart1.Legends(0).Enabled = False
Chart1.ChartAreas(0).AxisX.Interval = 1
End Sub
Private Shared Function GetData(ByVal query As String) As DataTable
Dim constr As String = "Data Source=.\SQL2014;Initial Catalog=Northwind;User ID=sa;Password=pass@123"
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Function
End Class
Screenshot