Introduction
In this article, we will see how to use the Chart control in Windows Forms Applications. As we know Charts and Graphs make data easier to understand and interpret. A chart is used to present the data in a visual form.
Let's Begin
Step 1
Open Visual Studio (I am using Visual Studio 2012) and create a new Windows Forms Application (select .NET Framework 4).
Step 2
Drop a Chart control from the Toolbox present in the Data tab.
Step 3
Go to Chart properties then click on Series.
Change the name of Series. Here, I set the name to Salary. We can also change the ChartType as well as appearance from the Series Collection Editor.
Go to the Form1.cs code and add the following lines of code:
- using System;
- using System.Windows.Forms;
-
- namespace DemoChart
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- fillChart();
- }
-
- private void fillChart()
- {
-
- chart1.Series["Salary"].Points.AddXY("Ajay", "10000");
- chart1.Series["Salary"].Points.AddXY("Ramesh", "8000");
- chart1.Series["Salary"].Points.AddXY("Ankit", "7000");
- chart1.Series["Salary"].Points.AddXY("Gurmeet", "10000");
- chart1.Series["Salary"].Points.AddXY("Suresh", "8500");
-
- chart1.Titles.Add("Salary Chart");
- }
- }
- }
Preview
Displaying Data in Chart control from the Database in Windows Forms Application
Step 1
Create a database (named Sample). Add a Table tbl_EmpSalary. The following is the table schema for creating tbl_EmpSalary.
Use the following preceding procedure. Add these lines of code to Form1.cs:
- using System;
- using System.Windows.Forms;
- using System.Data;
- using System.Data.SqlClient;
-
- namespace DemoChart
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
- fillChart();
- }
-
- private void fillChart()
- {
- SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
- DataSet ds = new DataSet();
- con.Open();
- SqlDataAdapter adapt = new SqlDataAdapter("Select Name,Salary from tbl_EmpSalary", con);
- adapt.Fill(ds);
- chart1.DataSource = ds;
-
- chart1.Series["Salary"].XValueMember = "Name";
-
- chart1.Series["Salary"].YValueMembers = "Salary";
- chart1.Titles.Add("Salary Chart");
- con.Close();
-
- }
- }
- }
Final Preview
I hope you like it. Thanks.