Saturday, January 19, 2013

Using GridView Template Fields

If you want to place multiple values in the same cell, or you have the unlimited ability to customize the content in a cell by adding HTML tags and server controls, you need to use a TemplateField.

The TemplateField allows you to define a completely customized template for a column. Inside the template you can add control tags, arbitrary HTML elements, and data binding expressions. You have complete freedom to arrange everything the way you want. For example, imagine you want to create a column that combines the in stock, on order, and reorder level information for a product. To accomplish this trick, you can construct an ItemTemplate like this:

<asp:TemplateField HeaderText="Status">
<b>In Stock:</b>
<%# Eval("UnitsInStock") %><br />
<b>On Order:</b>
<%# Eval("UnitsOnOrder") %><br />
<%# Eval("ReorderLevel") %>

To create the data binding expressions, the template uses the Eval() method, which is a static method of the System.Web.UI.DataBinder class. Eval() is an indispensable convenience—it automatically retrieves the data item that’s bound to the current row, uses reflection to find the matching field, and retrieves the value.

You’ll notice that this example template includes three data binding expressions. These expressions get the actual information from the current row. The rest of the content in the template defines static text, tags, and controls. You also need to make sure the data source provides these three pieces of information. If you attempt to bind a field that isn’t present in your result set, you’ll receive a runtime error. If you retrieve additional fields that are never bound to any template, no problem will occur.

Here’s the revised data source with these fields:

<asp:SqlDataSource ID="sourceProducts" runat="server"
ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT ProductID, ProductName, UnitPrice, UnitsInStock,
UnitsOnOrder,ReorderLevel FROM Products"
UpdateCommand="UPDATE Products SET ProductName=@ProductName,
UnitPrice=@UnitPrice WHERE ProductID=@ProductID">

When you bind the GridView, it fetches the data from the data source and walks through the collection of items. It processes the ItemTemplate for each item, evaluates the data binding expressions, and adds the rendered HTML to the table. You’re free to mix template columns with other column types. Figure shows an example with several normal columns and the template column at the end.

No comments:
Write comments
Recommended Posts × +