In this article I will explain with an example, how to fetch (retrieve) data from database using
DataTable 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
The following form consists of:
DataGridView – For displaying data.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Binding data to DataGridView from Database using DataTable
Inside the Form Load event handler, first the connection is read from App.Config file.
Then, the records are fetched from the Customers Table of Northwind database.
Finally, DataTable is assigned to the DataSource property of DataGridView.
C#
private void Form1_Load(object sender, EventArgs e)
{
string sql = "SELECT * FROM Customers";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dgvCustomers.DataSource = dt;
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim sql As String = "SELECT * FROM Customers"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
dgvCustomers.DataSource = dt
End Using
End Using
End Using
End Sub
Screenshot
Downloads