In this article I will explain with an example, how to fetch (retrieve) data from Database using DataTable with C# and VB.Net.
This article will illustrate how to populate DataGridView with data from SQL Server Database using SqlDataAdapter and DataTable in Windows Forms (WinForms) Application with C# and VB.Net.
For this article I am making use of the Microsoft’s Northwind Database. Download and install instructions are provided in the link below.
Adding a DataGridView to the Windows Form
Firstly you need to add a DataGridView control to the Windows Form from the Visual Studio ToolBox as shown below.
You will need to import the following namespaces.
Fetch (Retrieve) data from Database using DataTable with C# and VB.Net
Inside the Form Initialize event handler, BindGrid method is called.
Inside BindGrid method, first a connection to the database is established using the SqlConnection class and then the SqlCommand is initialized with the SQL to be executed.
Finally SqlDataAdapter object is initialized with the SqlCommand and using the Fill function, the DataTable is populated with the records returned from the executed SQL statement.
public partial class Form1 : Form
private void BindGrid()
string constring = @"Data Source=.\SQL2005;Initial Catalog=Northwind;User id = sa;password=pass@123";
using (SqlConnection con = new SqlConnection(constring))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
using (DataTable dt = new DataTable())
dataGridView1.DataSource = dt;
Public Class Form1
Public Sub New()
Private Sub BindGrid()
Dim constring As String = "Data Source=.\SQL2005;Initial Catalog=Northwind;User id = sa;password=pass@123"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("SELECT * FROM Customers", con)
cmd.CommandType = CommandType.Text
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
dataGridView1.DataSource = dt