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; } } }