HTML Markup: Asp Gridview Columns Asp Boundfield Asp Boundfield Asp Boundfield Asp Boundfield Columns Asp Gridview
HTML Markup: Asp Gridview Columns Asp Boundfield Asp Boundfield Asp Boundfield Asp Boundfield Columns Asp Gridview
Net using C#
HTML Markup
The following HTML Markup consists of an ASP.Net GridView Control which will be
populated using Generic List of Custom Business Objects.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns = "false"
AllowPaging = "true" OnPageIndexChanging = "OnPaging">
<Columns>
<asp:BoundField DataField = "CustomerId" HeaderText = "Customer Id" />
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:BoundField DataField = "City" HeaderText = "City" />
<asp:BoundField DataField = "Country" HeaderText = "Country" />
</Columns>
</asp:GridView>
The following class named Customer will be used to populate the GridView control with
records from database table. The class has four properties i.e. CustomerId, ContactName,
City and Country.
public class Customer
{
string _customerId;
public string CustomerId
{
get
{
return _customerId;
}
set
{
_customerId = value;
}
}
string _contactName;
public string ContactName
{
get
{
return _contactName;
}
set
{
_contactName = value;
}
}
string _city;
public string City
{
get
{
return _city;
}
set
{
_city = value;
}
}
string _country;
public string Country
{
get
{
return _country;
}
set
{
_country = value;
}
}
}
Namespaces
You will need to import the following namespaces.
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Inside the following function, the records from the Customers table of the Northwind
Database are fetched using DataReader and inside the WHILE loop a Generic List
consisting of the objects of the Customer class is populated.
private List<Customer> PopulateData()
{
string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
List<Customer> customers = new List<Customer>();
while (sdr.Read())
{
customers.Add(new Customer());
customers[customers.Count - 1].CustomerId = sdr["CustomerID"].ToString();
customers[customers.Count - 1].ContactName =
sdr["ContactName"].ToString();
customers[customers.Count - 1].City = sdr["City"].ToString();
customers[customers.Count - 1].Country = sdr["Country"].ToString();
}
con.Close();
return customers;
}
}
}
}
The following function populates the GridView control with the Generic List of Customer
class objects.
private void BindGrid(List<Customer> customers)
{
gvCustomers.DataSource = customers;
gvCustomers.DataBind();
}