[ASP.NET] GridView Templates

In a simple application, the GridView’s built-in field controls will do the job for you. But in professional applications, you definitely want to tweak the default display. A Template is a place-holder for controls and HTML tags.  

1. TemplateField

By converting a column to a “TemplateField“, you can define a customized template for a column. You can define multiple templates in a “TemplateField“.

public class TemplateField : DataControlField
{
  public ITemplate ItemTemplate { get; set; }
  public ITemplate AlternatingItemTemplate { get; set; }
  public ITemplate HeaderTemplate { get; set; } 
  public ITemplate FooterTemplate { get; set; }
  public ITemplate EditItemTemplate { get; set; }
  public ITemplate InsertItemTemplate { get; set; }
}

2. Data Binding Expressions

To create a data binding expression, you need to use the static method of “System.Web.UI.DataBinder” class; “Eval()”.

<%# Eval(“Price”, “{0:C}”) %>

The “Eval()” is read-only. It only reads a value from source. If you want to update or insert, you can use the “Bind()”.

3. Multiple Templates

  • HeaderTemplate: header
  • FooterTemplate: footer
  • ItemTemplate: each data cell
  • AlternatingItemTemplate: data cell in every other row
  • SelectedItemTemplate: data cell in a selected row
  • SeparatorTemplate: the separation of each item and alternate item
  • EditItemTemplate: a data cell in edit mode
<asp:GridView ID="productCategoryGV" runat="server" AutoGenerateColumns="False"
  DataKeyNames="ProductCategoryID" DataSourceID="productCategorySqlDS">
  <Columns>
    <asp:CommandField ShowEditButton="True" />
    <asp:BoundField DataField="ProductCategoryID" HeaderText="ID" ReadOnly="True" />
    <asp:BoundField DataField="Name" HeaderText="Name" />
    <asp:TemplateField HeaderText="Modified Date" SortExpression="ModifiedDate">
      <EditItemTemplate>
        <asp:Calendar ID="Calendar1" runat="server"
          SelectedDate='<%# Bind("ModifiedDate") %>'
          VisibleDate='<%# Eval("ModifiedDate") %>' >
        </asp:Calendar>
      </EditItemTemplate>
      <ItemTemplate>
        <asp:Label ID="Label1" runat="server"
          Text='<%# Bind("ModifiedDate", "{0:MM/dd/yyyy}") %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

<asp:SqlDataSource ID="productCategorySqlDS" runat="server"
  ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"
  SelectCommand="SELECT [ProductCategoryID], [Name], [ModifiedDate] FROM [Production].[ProductCategory]"
  UpdateCommand="UPDATE [Production].[ProductCategory] SET [Name] = @Name, [ModifiedDate] = @ModifiedDate WHERE [ProductCategoryID] = @ProductCategoryID">
  <UpdateParameters>
    <asp:Parameter Name="Name" Type="String" />
    <asp:Parameter Name="ModifiedDate" Type="DateTime" />
    <asp:Parameter Name="ProductCategoryID" Type="Int32" />
  </UpdateParameters>
</asp:SqlDataSource>

4. Handling Events

What if you want to handle events triggered by a control inside a Template? The GridView creates multiple copies of that control. How can you determine which caused the event?

The answer is using the Event Bubbling. You are not attaching the handler to the control directly. The event is captured in the “RowCommand” event of the “GridView“.

  • The control in a Template: Set the “CommandName” and the “CommandArgument” properties
  • GridView control: Add the handler to the “RowCommand” event
  • Event Handler: Check the “CommandName” and use the “CommandArgument” value to see which row triggers the event
<asp:GridView ID="productCategoryGV" ... onrowcommand="productCategoryGV_RowCommand">
  <Columns>
    ...
    <asp:TemplateField HeaderText="Greet">
      <ItemTemplate>
        <asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("Name") %>'
          CommandName="Greet" Text="Say Hi" />
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

<asp:Label ID="lblInfo" runat="server"></asp:Label>
protected void productCategoryGV_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Greet")
  {
    lblInfo.Text = "Hello, it is from " + e.CommandArgument.ToString();
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s