In this article I will explain with an example, how to bind / fill/ populate DataTable from Database in ASP.Net using C# and VB.Net.
 
 
Database
I have made use of the following table Customers with the schema as follows.
Bind / Fill / Populate DataTable from Database in ASP.Net using C# and VB.Net
I have already inserted few records in the table.
Bind / Fill / Populate DataTable from Database in ASP.Net using C# and VB.Net
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
 
Bind / Fill / Populate DataTable from Database
Inside the Page Load event of the page, the DataTable is populated with the records of the Customers Table.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, Name, Country FROM Customers"))
            {
                cmd.Connection = con;
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                }
            }
        }
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("SELECT CustomerId, Name, Country FROM Customers")
                cmd.Connection = con
                Using sda As New SqlDataAdapter(cmd)
                    Dim dt As New DataTable()
                    sda.Fill(dt)
                End Using
            End Using
        End Using
    End If
End Sub
 
 
Screenshot
The following screenshot displays the DataTable populated from database.
Bind / Fill / Populate DataTable from Database in ASP.Net using C# and VB.Net
 
 
Downloads