In this article I will explain with an example, how to use SqlDataReader in Windows Forms (WinForms) Application using C# and VB.Net.
What is SqlDataReader?
The
SqlDataReader class is used to read data from the
SQL Server database.
The SqlDataReader uses connection-oriented architecture i.e. it requires an open connection to the Data Source while reading the data.
The data is available as long as the connection with the database exists. You need to open and close the connection explicitly.
It reads data in the forward-only direction. Once a record is read, then the next record will be read.
There is no way to go back and read the previous record.
The SqlDataReader class has some properties.
1. Connection - Gets the SqlConnection associated with the SqlDataReader.
2. HasRows - Gets a value that indicates whether the SqlDataReader contains one or more rows.
3. IsClosed - Retrieves a Boolean value that indicates whether the specified SqlDataReader instance has been closed.
4. RecordsAffected - Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement.
5. FieldCount - Gets the number of columns in the current row.
Note: For more details about
SqlDataReader, please refer
MSDN.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Form Design
The following Form consists of:
DataGridView – For displaying data.
Namespaces
You will need to import the following namespaces.
C#
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data.SqlClient
Imports System.Configuration
Public Class
The public class consists of following properties.
C#
public class Customer
{
public string CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
VB.Net
Public Class Customer
Public Property CustomerId As String
Public Property Name As String
Public Property Country As String
End Class
Implementing SqlDataReader in C# and VB.Net
Inside the Form Load event handler, the BindGrid method is called.
BindGrid
Inside the BindGrid method, first the connection string is read from App.Config file.
Then, an object of SqlCommand class is created and the SELECT query is passed to it as parameter and the Generic List collection of Customer class is created.
The connection is opened and an object of SqlDataReader is created and the ExecuteReader function is executed.
Then, a WHILE loop is executed and fetched records are added to the Generic List collection of Customer class object.
Finally, the Generic List collection of Customer class object is assigned to the DataSource property of DataGridView and the DataGridView is populated.
Note: Here Generic List collection is used, but SqlDataReader can be directly used to populate DataSet or DataTable.
C#
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string sql = "SELECT CustomerId, ContactName, Country FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
List<Customer> customers = new List<Customer>();
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new Customer
{
CustomerId = sdr["CustomerId"].ToString(),
Name = sdr["ContactName"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
dgvCustomers.DataSource = customers;
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim sql As String = "SELECT CustomerId, ContactName, Country FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand(sql, con)
Dim customers As List(Of Customer) = New List(Of Customer)()
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
customers.Add(New Customer With {
.CustomerId = sdr("CustomerId").ToString(),
.Name = sdr("ContactName").ToString(),
.Country = sdr("Country").ToString()
})
End While
End Using
con.Close()
dgvCustomers.DataSource = customers
End Using
End Using
End Sub
Screenshot
Downloads