Creating the Home Page for a Simple Storefront with LINQ - ItemTemplate
(Page 2 of 4 )
Next comes the ItemTemplate, which is the template for an individual item in the ListView. Place this alongside the LayoutTemplate:
<ItemTemplate>
<div>
<img src="ProductPicture.aspx?id=<%#Eval("ProductID") %>" alt="Product Picture" />
<br />
<strong><a href="Product.aspx?id=<%#Eval("ProductID") %>">
<%#Eval("Name") %>
</a></strong>
</div>
</ItemTemplate>
The above displays a picture of the product, the name of the product, and a link to view the product (though, of course, the view functionality is not done). We access the various fields of the entry using Eval, passing in the appropriate field's name. When the page is viewed, the code tags are, of course, replaced with the appropriate values.
It doesn't take much to see that the above markup will generate a very primitive list of items, but we'll worry about replacing the layout in a moment. Right now we need to wire up our ListView. There are two ways we can databind our control using LINQ and ASP.NET. The first way is to databind it directly through code, and the second way is to use LinqDataSource. Here, we're going to use the first method and manually databind it in Page_Load. We'll discuss the second method in a bit.
To databind the control, we simply need to query the database using LINQ as we would in a normal application, and then we need to assign the result to the ListView control's DataSource attribute. Finally, we need to call the DataBind method. Here's how it's done:
protected void Page_Load(object sender, EventArgs e)
{
AdventureWorksDataContext db = new AdventureWorksDataContext();
var latestItems = (from p in db.Products
orderby p.SellStartDate descending
select p).Take(3);
LatestItemsView.DataSource = latestItems;
LatestItemsView.DataBind();
}
The only thing strange in the code, perhaps, is Take. Take simply limits the amount of items returned. Here, we get the first three results. Besides Take, in the query, we order the table's entries by the SellStartData field, in reverse. This will make it so the latest items are first, and the oldest items are last.
Run the page, and you should see the three latest products:

Don't be alarmed by the “No Image Available” pictures. Many of the items, unfortunately, don't include real pictures. Instead, they use a “No Image Available” graphic. But at least we know that the ProductPicture.aspx page is properly working.
Next: A New Style >>
More .NET Articles
More By Peyton McCullough