C # example
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Template.aspx.cs" Inherits="Template" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Using System; using System. data; using System. configuration; using System. collections; using System. web; using System. web. security; using System. web. UI; using System. web. UI. webControls; using System. web. UI. webControls. webParts; using System. web. UI. htmlControls; public partial class Template: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {if (! IsPostBack) {// declare TemplateField customField; // generate a new TemplateField customField = new TemplateField (); // set the TemplateField Header customField. headerTemplate = new GridViewTemplate (DataControlRowType. header, "Custom fields"); // sets the Data customField of the TemplateField. itemTemplate = new GridViewTemplate (DataControlRowType. dataRow, "id"); // Add TemplateField to the GridView this. gridView1.Columns. add (customField); customField = new TemplateField (); customField. headerTemplate = new GridViewTemplate (DataControlRowType. header, "name"); customField. itemTemplate = new GridViewTemplate (DataControlRowType. dataRow, "name"); this. gridView1.Columns. add (customField) ;}} public class GridViewTemplate: ITemplate {private DataControlRowType templateType; private string columnName; public GridViewTemplate (DataControlRowType, string colname) {templateType = type; columnName = colname ;}
// When implemented by a class, defineControlObject. Then define these child controls in the inline template.
public void InstantiateIn(System.Web.UI.Control container) { switch (templateType) { case DataControlRowType.Header: Literal lc = new Literal(); lc.Text = "<B>" + columnName + "</B>"; container.Controls.Add(lc); break; case DataControlRowType.DataRow: Label data = new Label(); data.DataBinding += new EventHandler(data_DataBinding); container.Controls.Add(data); break; default: break; } } private void data_DataBinding(object sender, EventArgs e) { Label l = (Label)sender; GridViewRow row = (GridViewRow)l.NamingContainer; l.Text = DataBinder.Eval(row.DataItem,columnName).ToString(); }}
Execution result: