Hi nauna,
You have to return a list and then bind the list to gridview.
Check the below example.
HTML
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Namespaces
C#
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Code
DataAccess.cs
public class DataAccess
{
public int Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public List<DataAccess> GetCustomers()
{
List<DataAccess> Customers = new List<DataAccess>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
Id = Convert.ToInt32(sdr["CustomerId"]);
Name = sdr["Name"].ToString();
Country = sdr["Country"].ToString();
Customers.Add(new DataAccess { Id = Id, Name = Name, Country = Country });
}
con.Close();
}
}
return Customers;
}
}
DataAccess.vb
Public Class DataAccess
Public Property Id As Integer
Public Property Name As String
Public Property Country As String
Public Function GetCustomers() As List(Of DataAccess)
Dim Customers As List(Of DataAccess) = New List(Of DataAccess)()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers", con)
con.Open()
Dim sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Id = Convert.ToInt32(sdr("CustomerId"))
Name = sdr("Name").ToString()
Country = sdr("Country").ToString()
Customers.Add(New DataAccess With {
.Id = Id,
.Name = Name,
.Country = Country
})
End While
con.Close()
End Using
End Using
Return Customers
End Function
End Class
Default.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataAccess access = new DataAccess();
gvCustomers.DataSource = access.GetCustomers();
gvCustomers.DataBind();
}
}
Default.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Dim access As DataAccess = New DataAccess()
gvCustomers.DataSource = access.GetCustomers()
gvCustomers.DataBind()
End If
End Sub
Screenshot