ASP.NET - Creating Template Field in Grid View
What is a template Field? A template field is nothing but placing standard controls
within the GridView. GridView provides some of the controls which are more or less
equivalent to the standard controls like TextBox, Checkbox etc.
But sometimes, we may have to place some other standard control within the GridView
for better programming and better user experience. In this time we will be going
for a template field. Template field also enables us to place controls in header
and footer also. For example, we want to place a control in the footer area of the
GridView in order to display the total of a column of want to display the total
number of records in the footer. Then I use the template field.
Let us see how to display Total number of records available in the footer of the
gridview.
Use the following steps to prepare display the footer in Gridview.
- Insert a GridView in a form.
- In this example we want to show Total number of records in the footer, we need to
make sure to display the Footer of the GridView. By default it is False. Choose the GridView. Press F4 to make the properties window visible. Make sure to
set the ShowFooter to True.

- Open the GridView Tasks Menu and choose the first column and convert into a
template field as shown below:

- Using GridView Tasks menu, choose the Edit Templates menu.

- From the Combobox, choose Footer Template to insert controls in it.

- Insert a label control lblTotalRecords.

- Now from the GridView Tasks menu, choose end edit template.

- Make sure to assign the required datasource to the Gridview property through code.
If you don't know how to do this, please refere to
Listing of Records in Grid View.
- Additionally add the following code in the RowDataBound event of the Gridview. The
coding concept is very simple. At the time of rendering the output to the browser,
we are picking up the label control and assign the value to it.
Protected Sub gvList_RowDataBound(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
Handles gvList.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.Footer
Dim lbl As Label
lbl = e.Row.FindControl("lblTotalRecords")
lbl.Text = "Total : " & CType(gvList.DataSource, _
DataTable).Rows.Count
End Select
End Sub
- Run to view the result, like the one given below:

|
|
|
|
|
|