In this article I will explain with an example, how to fetch (retrieve) data from Database using DataReader with C# and VB.Net.
This article will illustrate how to populate DataGridView with data from SQL Server Database using SqlDataReader and DataTable in Windows Forms (WinForms) Application with C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
Form Controls
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
Fetch (Retrieve) data from Database using DataReader with C# and VB.Net
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).
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