In this article I will explain with an example, how to connect SQL Server Database to DataGridView in Windows Forms (WinForms) Application using C# and VB.Net.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 
Form Design
You need to add a DataGridView control to the Windows Form.
How to Connect SQL Server Database to DataGridView in Windows
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Data.SqlClient
 
 
Populate DataTable using SqlDataAdapter in C# and VB.Net
Inside the Form Load event handler, BindGrid method is called.
Inside BindGrid method, SqlDataAdapter object is initialized with the SqlCommand and using the Fill function, the DataTable is populated with the records from database.
Finally, the DataTable is used to populate the DataGridView.
C#
private void Form1_Load(object sender, EventArgs e)
{
    this.BindGrid();
}
 
private void BindGrid()
{
    string constring = @"Data Source=.\SQL2019;Initial Catalog=Northwind;User id=sa;password=pass@123";
    using (SqlConnection con = new SqlConnection(constring))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, Country FROM Customers", con))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    dataGridView1.DataSource = dt;
                }
            }
        }
    }
}
 
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Me.BindGrid()
End Sub
 
Private Sub BindGrid()
    Dim constring As String = "Data Source=.\SQL2019;Initial Catalog=Northwind;User id=sa;password=pass@123"
    Using con As New SqlConnection(constring)
        Using cmd As New SqlCommand("SELECT CustomerId, ContactName, Country FROM Customers", con)
            Using sda As New SqlDataAdapter(cmd)
                Using dt As New DataTable()
                    sda.Fill(dt)
                    dataGridView1.DataSource = dt
                End Using
            End Using
        End Using
    End Using
End Sub
 
 
Screenshot
How to Connect SQL Server Database to DataGridView in Windows
 
 
Downloads