Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

Creating a Custom Column in a GridView Web Server Control

The GridView control can automatically generate columns from the fields provided by the data source. In addition, you can create a collection of columns to be displayed instead of automatically generating them. However, you might encounter a scenario where you need to customize how an individual column is displayed. In that case, you can create a TemplateField to specify a custom column layout.

A TemplateField object enables you to specify templates that contain markup and controls to customize the layout and behavior of a column in a GridView control. Using an ItemTemplate, you can specify the layout to be used when the GridView displays data in a column. To specify custom layout for when users edit data in a column, you can create an EditItemTemplate.

Your template can contain markup, Web server controls, and command buttons. For more information on templates, see ASP.NET Web Server Controls Templates.

In a template, you can bind controls to data using the Eval and Bind methods. You use the Eval method when the control will only display values. You use the Bind method when users can modify a data value—that is, for data-update scenarios. You can use the Eval method in any of the templates to display data. You use the Bind method in a template with controls in which users might change values, such as TextBox and CheckBox controls, or a template that allows a record to be deleted. For more information, see Data-Binding Expressions Overview.

The following example shows the Columns collection of a GridView control. The collection contains a TemplateField object, which in turn contains an ItemTemplate object. To display a date, the ItemTemplate includes a Label control that uses the Eval method. To edit a date, the other templates use a Calendar control that uses the Bind method.

  <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" ReadOnly="true"/>                    
  <asp:BoundField DataField="FirstName"  HeaderText="First Name"/>
  <asp:BoundField DataField="LastName"   HeaderText="Last Name"/>                    
  <asp:TemplateField HeaderText="Birth Date">
      <asp:Label ID="BirthDateLabel" Runat="Server" 
                 Text='<%# Eval("BirthDate", "{0:d}") %>' />
      <asp:Calendar ID="EditBirthDateCalendar" Runat="Server"
                    VisibleDate='<%# Eval("BirthDate") %>'
                    SelectedDate='<%# Bind("BirthDate") %>' />
  <asp:HyperLinkField Text="Show Detail"
                      DataNavigateUrlFields="EmployeeID" />                   

Community Additions

© 2015 Microsoft