C# Displaying SQL Server Data in a DataGridView: A Step-by-Step Guide

In this tutorial, we will delve into the world of database programming with C#. Specifically, we will learn how to retrieve data from an SQL Server database and display it in a DataGridView. This is a powerful technique that can greatly enhance the user experience of your Windows Forms applications.

What is DataGridView?

DataGridView is a versatile control in Windows Forms applications that allows you to display and manipulate tabular data. It’s highly customizable and can be used to display data from various sources, including databases.

Our Application

Our application consists of a single method, ViewGridView, which retrieves data from an SQL Server database and displays it in a DataGridView. The goal is to display the data in a way that’s easy to read and understand.

The Code

The core of our application lies in the ViewGridView method. Here’s what it looks like:

string connectionString = "Data Source=VICH-PC\\SQLEXPRESS01;Initial Catalog=ShaneCambodiaDB;User Id=Vich;Password=123456789;";

private void ViewGridView()
{
    string query = "Select * From EmployeeInfo";

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        SqlDataAdapter dataAdapter = new SqlDataAdapter(query, conn);
        
        DataTable dt = new DataTable();
        dataAdapter.Fill(dt);

        GridView.DataSource = dt;

        foreach (DataGridViewColumn col in GridView.Columns)
        {
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        }
    }
}

This method first establishes a connection to the SQL Server database using a connection string. It then creates a new SqlDataAdapter with a SQL query and the connection object. The SqlDataAdapter fills a DataTable with the results of the query. This DataTable is then set as the DataSource for the DataGridView.

Finally, the method iterates over each column in the DataGridView and sets the alignment of the header cell and default cell style to DataGridViewContentAlignment.MiddleCenter. This centers the text in each cell, making the data easier to read.

Conclusion
And that’s it! With this setup, you can easily retrieve data from an SQL Server database and display it in a DataGridView. This technique can be extended to manage as many tables as you need in your application. It’s a simple yet powerful way to enhance the user experience of your Windows Forms applications.

I hope this helps! Let me know if you need any further assistance. Happy coding! 🚀

Post a Comment

Previous Post Next Post