Hi ernestpauld,
I have created a sample using the Customers, Orders and the Employees tables of Northwind database.
You can download using the link given below.
Download Northwind Database
Form Design
The Form consists of a DataGridView control.
Namespaces
You need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Code
Inside the Form Load event handler, first a SQL query is generated which will be used to fetch data from the Customers, Orders and Employees tables of the Northwind database with the help of INNER JOIN.
Then the SQL query is passed to the SqlDataAdaper along with SqlConnection and fetches the records into a DataTable.
Finally, the returned DataTable is used to populate the DataGridView.
C#
private void Form1_Load(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
string constring = @"Data Source=.\SQL2022;Initial Catalog=Northwind;User id=sa;password=pass@123";
using (SqlConnection con = new SqlConnection(constring))
{
string sql = "SELECT TOP 5 c.CustomerId, c.ContactName, o.OrderId,";
sql += " (e.FirstName + ' ' + e.LastName) EmployeeName";
sql += " FROM Customers c INNER JOIN Orders o on c.CustomerId = o.CustomerId";
sql += " INNER JOIN Employees e ON e.EmployeeId = o.EmployeeId";
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.BindGrid()
End Sub
Private Sub BindGrid()
Dim constring As String = "Data Source=.\SQL2022;Initial Catalog=Northwind;User id=sa;password=pass@123"
Using con As New SqlConnection(constring)
Dim sql As String = "SELECT TOP 5 c.CustomerId, c.ContactName, o.OrderId,"
sql += " (e.FirstName + ' ' + e.LastName) EmployeeName"
sql += " FROM Customers c INNER JOIN Orders o on c.CustomerId = o.CustomerId"
sql += " INNER JOIN Employees e ON e.EmployeeId = o.EmployeeId"
Using sda As New SqlDataAdapter(sql, con)
Using dt As New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
Screenshot