Creating a WPF Application to Display GDP Data from SQL Server

In this article, we will walk through building a simple WPF (Windows Presentation Foundation) application in C# that connects to a SQL Server database, retrieves GDP data, and displays it in a DataGrid. This application serves as an excellent introduction to WPF applications and database operations in C#.

Prerequisites

  1. Visual Studio: Make sure you have Visual Studio installed with the .NET desktop development workload.
  2. SQL Server: You need a local or cloud-based SQL Server instance running, along with a database containing a table named GDP_Join within the wb schema.

Project Setup

  1. Create a WPF Application:
  • Open Visual Studio.
  • Select Create a new project.
  • Choose WPF App (.NET Framework).
  • Name your project (e.g., WpfApp1) and click Create.
  1. Add References:
  • Ensure your project has references to System.Data and System.Net.Http for database access and HTTP requests, respectively.
  1. Create the User Interface:
  • Open MainWindow.xaml and define a DataGrid in the window to display GDP data.
   <Window x:Class="WpfApp1.MainWindow"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           Title="GDP Data" Height="450" Width="800">
       <Grid>
           <DataGrid x:Name="Tabela" AutoGenerateColumns="True" SelectionChanged="DataGrid_SelectionChanged" />
       </Grid>
   </Window>

Code Implementation

Next, let’s dive into the C# code behind MainWindow.xaml.cs. This code is responsible for establishing a connection to the SQL Server database, executing a query to retrieve GDP data, and populating the DataGrid with the results.

The Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Net.Http;
using System.Data;
using System.Configuration;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            LoadData();
        }

        private void LoadData()
        {
            Tabela.ItemsSource = GetData().DefaultView;
        }

        public DataTable GetData()
        {
            DataTable dataTable = new DataTable();
            string connectionString = "Data Source=localhost;Initial Catalog=wb;Integrated Security=True;";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string query = @"SELECT * FROM [wb].[dbo].[GDP_Join]";
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(dataTable);
                }
            }
            return dataTable;
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // Handle selection change if necessary
        }
    }
}

Code Explanation

  • Namespace and References:
  • The application uses several namespaces for functionalities like data manipulation (System.Data), SQL connection (System.Data.SqlClient), and WPF components.
  • MainWindow Class:
  • This class is the primary interface for our application. It inherits from Window.
  • Constructor:
  • In the constructor, LoadData() is called to fetch and display the GDP data as soon as the application starts.
  • LoadData Method:
  • This method binds the result of GetData() to the ItemsSource of the DataGrid, allowing the data to be displayed.
  • GetData Method:
  • This method creates a DataTable to hold the data retrieved from the database.
  • A connection string is defined to connect to SQL Server, where:
    • Data Source specifies the server.
    • Initial Catalog specifies the database name.
    • Integrated Security=True uses Windows Authentication to connect.
  • A SqlCommand is created with a SQL query to select all data from the GDP_Join table.
  • A SqlDataAdapter is used to fill the DataTable with the results of the query.
  • DataGrid_SelectionChanged Event:
  • This method can be used to handle any actions when the selected item in the DataGrid changes. It’s currently empty but can be customized for specific actions.

Running the Application

  1. Ensure your SQL Server is running and contains the GDP_Join table with appropriate data.
  2. Build and run the WPF application from Visual Studio.
  3. Upon launching, the DataGrid will populate with GDP data from your SQL Server database.

Conclusion

This WPF application provides a foundational understanding of how to retrieve and display data from an SQL Server database using C#. The structure of the application is straightforward, making it a good starting point for those looking to learn more about WPF and database interactions. You can further enhance the application by adding features such as filtering, sorting, or editing data directly in the DataGrid. Happy coding!

Edvaldo Guimrães Filho Avatar

Published by

Categories: