In this article I will explain how to populate (bind) DataGridView using DataReader (SqlDataReader) in Windows Forms (WinForms) Application using C# and VB.Net.
Windows Forms DataGridView does not support DataReader (SqlDataReader) and hence when we try to bind DataGridView to DataReader (SqlDataReader), the DataGridView does not show any records.
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
Form Controls
In the below Form, there’s a DataGridView which will be populated from Database using DataReader.
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
Populating the DataGridView using DataReader
Inside the Form Load event, a Select Query is executed over the Customers table of the Northwind database and results are fetched using DataReader (SqlDataReader).
The SqlDataReader is then loaded into a DataTable and 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=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, Country FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
con.Close();
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim constring As String = "Data Source=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("SELECT CustomerId, ContactName, Country FROM Customers", con)
cmd.CommandType = CommandType.Text
con.Open()
Dim dt As New DataTable()
dt.Load(cmd.ExecuteReader())
dataGridView1.DataSource = dt
con.Close()
End Using
End Using
End Sub
Screenshot
Downloads