How to Link Chart /Graph with Database in C#

By FoxLearn 12/9/2024 2:20:33 PM   16.05K
Linking a chart or graph with a database in C# involves querying the database to fetch data and then using the data to populate the chart or graph.

This article explains how to integrate database operations (loading and saving) with a chart visualization in a Windows Forms application using C#.

How to Link Chart /Graph with Database in C#?

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "ChartDemo" and then click OK

Create a local database, then add a AgeStatistic table to your database -> create a dataset then drag the AgeStatistic table to your dataset as shown below.

c# dataset

Design your form as shown below.

chart c#

Initialize the Form and Load Data

private void Form1_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'database.AgeStatistics' table. You can move, or remove it, as needed.
    this.ageStatisticsTableAdapter.Fill(this.database.AgeStatistics);
}

Loads data from the AgeStatistics table into the bound DataSet (database) on form initialization.

Save Changes to the Database

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        // Update data to sql database
        ageStatisticsBindingSource.EndEdit(); // Ensures that any pending edits are committed to the data source.
        ageStatisticsTableAdapter.Update(database.AgeStatistics); // Updates changes in the bound DataSet (database) back to the database.
        MessageBox.Show("Your data has been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Load Data into the Chart

private void btnLoad_Click(object sender, EventArgs e)
{
    // Set the chart's data source and bind data
    chart1.Series["Age"].XValueMember = "Age";
    chart1.Series["Age"].YValueMembers = "Total";
    chart1.DataSource = database.AgeStatistics;
    chart1.DataBind();
}

These map the X and Y axes to the Age and Total columns in the data source.

You need to place a Chart control on your form and name it chart1. Ensure that the Series name is set to "Age" in the properties window.

VIDEO TUTORIAL