Hi Mohal,
Please refer below sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Code
C#
private void Form1_Load(object sender, EventArgs e)
{
BindGrid();
}
private void BindGrid()
{
DataTable dt = new DataTable();
string cs = @"Server=192.168.0.100\SQL2019;Database=Northwind;UID=sa;PWD=pass@123";
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand("SELECT CustomerId,ContactName,Country FROM Customers", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
DataTable dtResult = new DataTable();
if (dt.Rows.Count > 0)
{
dtResult = dt.AsEnumerable().Take(5).CopyToDataTable();
}
gvCustomers.DataSource = dtResult;
}
VB.Net
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
BindGrid()
End Sub
Private Sub BindGrid()
Dim dt As DataTable = New DataTable()
Dim cs As String = "Server=192.168.0.100\SQL2019;Database=Northwind;UID=sa;PWD=pass@123"
Using con As SqlConnection = New SqlConnection(cs)
Using cmd As SqlCommand = New SqlCommand("SELECT CustomerId,ContactName,Country FROM Customers", con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
sda.Fill(dt)
End Using
End Using
End Using
Dim dtResult As DataTable = New DataTable()
If dt.Rows.Count > 0 Then
dtResult = dt.AsEnumerable().Take(5).CopyToDataTable()
End If
gvCustomers.DataSource = dtResult
End Sub
Screenshot