Displaying Data in Chart in VB
Displaying Data in Chart in VB
Displaying Data in Chart in VB
Net
This is a tutorial on how to add a chart to your visual basic .net application and
display data as graph.
I have a Microsoft Access database that holds information about Sales and
Expenses.
Table 1: Expenses: There are two fields in this table: Month, and Amount
Table 2: Sales: There are two fields in this table: Month, and Amount
The default chart comes with a default Series collection called Series1
The Series is the title of data that we are displaying. In this tutorial we will
display sales and expenses data from a database. Therefore our series
collection will be Sales, Expenses.
We will delete Series1 becuase we will replace it with Expenses and Sales.
Right click the chart and click on properties. In the properties window, scroll
down to Series and click on the small button next to Collection:
In the window that appears, click on Series1 in the left list, click
on Remove then Ok
Now I will add a button to the form, and start adding the code to the button
click event.
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs)
Handles Button1.Click
Chart1.Series.Add("Expenses")
Chart1.Series.Add("Sales")
End Sub
Now I will add the code that will handle the connection to the database:
Then add the following code inside the button click event to connect to your
Access database:
Dim Conn As OleDbConnection = New OleDbConnection
Dim provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile = "C:\Users\Jimmy\Desktop\Sales.accdb" ' Change it to your
Access Database location
Conn.ConnectionString = provider & dataFile
Conn.Open()
Then add the following code to the button click event to get the data from the
database and display it into the chart:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Month],
[Amount] FROM [Expenses]", Conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
Chart1.Series("Expenses").Points.AddXY(dr("Month").ToString,
dr("Amount").ToString)
End While
dr.Close()
cmd.Dispose()
This is the first look of the Chart after clicking the button and displaying the
data as graphs:
You can change many of the chart properties as background color, font, size
etc.