asp.net.ph

Skip Navigation Links

Adding Template Columns to a DataGrid Control

Controls You Can Use on Web Forms   ASP.NET Data Controls   DataGrid Control


A TemplateColumn is used in cases where authors need complete control over the contents of a DataGrid column. The TemplateColumn is declared with an <ItemTemplate> element, which in turn is used to define the content that will be rendered for each row in the column. The ItemTemplate can include any valid HTML.

The following sample demonstrates using a TemplateColumn to render an HTML IMG element for each row in a DataGrid control. To accomplish this, the image’s src property is set to a field in the data source, which typically contains the path to the image files. ASP.NET databinding syntax is used to output the field’s values.

To add a template column

  1. Set the DataGrid control’s AutoGenerateColumns property to false.
    <asp:datagrid id="myGrid" runat="server"
       autogeneratecolumns=false
       ...
    >
  2. Within the DataGrid declaration, declare a <Columns> element.
  3. Within the Columns element, define the <asp:TemplateColumn> control, along with the required <ItemTemplate> element.
  4. Within the ItemTemplate, define the HTML or server control that will contain the field value.

    To display the value of a field in an item template, use DataBinding Expression Syntax.

  5. Optionally set the <asp:TemplateColumn> control’s other properties. For syntax, see DataGrid Control Syntax.
    <columns>
    
       <asp:templatecolumn>
    
          <itemtemplate>
             <img width=60 align="top" 
                src='<%# Eval ( "title_id", "../images/title-{0}.gif" ) %>’ >
          </itemtemplate>
    
       </asp:templatecolumn>
    
       ...
    
    </columns>

The following examples show several ways of using a TemplateColumn to display a column with custom layout in a DataGrid control.

DataGrid TemplateColumn Example
Run Sample | View Source
DataGrid SelectedIndex Property
Run Sample | View Source
Enabling Multiple Item Deletions in a DataGrid
Run Sample | View Source

For addtional information, see TemplateColumn in the class library.

See Also

Adding Bound Columns to a DataGrid Control   Adding Button Columns to a DataGrid Control   Adding Hyperlink Columns to a DataGrid Control



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note