To start off with, we’ll create a new page within our
project called “Sample1.aspx”.
Within the Sample1.aspx file we’ll add a GridView server
control and explicitly define a few columns to display:
Listing 6
<%@ Page Language="C#" CodeFile="Sample1.aspx.cs" Inherits="Sample1" %>
<html>
<body>
<form id="form1" runat="server">
<h1>Northwind Customers</h1>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField HeaderText="Customer ID" DataField="CustomerID" />
<asp:BoundField HeaderText="Name" DataField="CompanyName" />
<asp:BoundField HeaderText="City" DataField="City" />
<asp:BoundField HeaderText="State" DataField="Region" />
</Columns>
</asp:GridView>
</form>
</body>
</html>
Within the Sample1.aspx.cs code-behind file we’ll add a
“using System.Query” statement at the top of the file, and then add LINQ code
within the Page_Load() event to retrieve all US customers from the Northwind
database, sorted by CompanyName, and programmatically bind the results to the
GridView control:
Listing 7
using System;
using System.Configuration;
using System.Web.UI;
using System.Query;
public partial class Sample1 : System.Web.UI.Page {
protected void Page_Load() {
string connectionString = ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
Northwind.Northwind db = new Northwind.Northwind(connectionString);
GridView1.DataSource = from customer in db.Customers
where customer.Country == "USA"
orderby customer.CompanyName
select customer;
GridView1.DataBind();
}
}
When we save the page and access it from a browser we’ll get
this output:
Figure 3
Disclaimer: I will leave it as an exercise to the reader to
write a nice CSS stylesheet to make it look pretty – but hopefully you get the
point of how the functionality works. J