In this article I will explain with an example, how to fill (populate) DataTable using SqlDataAdapter in 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;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Fill (Populate) DataTable using SqlDataAdapter in C# and VB.Net
Inside the Form Load event handler, first the connection is read and the SELECT query is defined.
Then, a connection to the database is established using the SqlConnection class.
The SqlDataAdapter object is initialized with the SqlCommand and using the Fill function, the DataTable is populated with the records from database.
Finally, the DataTable is assigned to the DataSource property of DataGridView and the DataGridView is populated.
C#
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string constr = @"Data Source=.\SQL2019;Initial Catalog=Northwind;User id = sa;password=pass@123";
string sql = "SELECT CustomerID, ContactName, Country FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
VB.Net
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim constr As String = "Data Source=.\SQL2019;Initial Catalog=Northwind;User id = sa;password=pass@123"
Dim sql As String = "SELECT CustomerID, ContactName, Country FROM Customers"
Using con As SqlConnection = New SqlConnection(constr)
Using sda AsSqlDataAdapter = New SqlDataAdapter(sql, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
Screenshot
Downloads