Hi ahmadsubuhanl...,
Check this example. Now please take its reference and correct your code.
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.Configuration;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand("SELECT TOP 5 CustomerID,ContactName,Country FROM Customers");
cmd.Connection = con;
con.Open();
SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(sdr);
con.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
string id = dt.Rows[i]["CustomerID"].ToString();
string name = dt.Rows[i]["ContactName"].ToString();
string country = dt.Rows[i]["Country"].ToString();
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand = New SqlCommand("SELECT TOP 5 CustomerID,ContactName,Country FROM Customers")
cmd.Connection = con
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As DataTable = New DataTable()
dt.Load(sdr)
con.Close()
For i As Integer = 0 To dt.Rows.Count - 1 Step 1
Dim id As String = dt.Rows(i)("CustomerID").ToString()
Dim name As String = dt.Rows(i)("ContactName").ToString()
Dim country As String = dt.Rows(i)("Country").ToString()
Next
End Using
End Sub
Screenshot