BLOGS BY TOPIC
BLOGS BY AUTHOR
BLOGS BY YEAR
The gridview control is at the heart of every ASP.NET webpage, displaying rows of data and allowing you to add, edit and delete records. This lengthy blog explains how to master this complex control.
- An introduction to GridView Controls
- Traps to Avoid when using Gridviews
- Creating GridView Controls
- Formatting Gridviews
- Template Fields / Template Columns (this blog)
- Conditional formatting (RowDataBound Events)
- You clicked on a Gridview? The RowCommand Event
- Sorting a Gridview
Posted by Andy Brown on 24 September 2012
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
Template Fields / Template Columns
What are Template Fields?
Gridview columns can contain virtually anything you like:
Here our gridview contains two image buttons in the final column.
In the above example, we have two bound columns followed by one template column or template field.
A template column gives you carte blanche to insert any combination of controls you like into a table cell.
Creating a Template Column
To create a template column, just open its tag:
Here we have 2 bound columns, but the 3rd one is going to be a template column.
You can now specify how different types of row will appear:
You can specify different things to appear, according to whether this is the header, footer, item or alternating item row of a gridview, and depending on whether you're in Edit mode or not.
For a simple gridview, you'll just use the item template (controlling what appears for each row of the grid):
The full HTML for the gridview columns shown above.
It's worth stressing that at this stage your buttons won't do anything - read on in the blog for how to handle events for your gridview.
Note that for this example we could have put each button in its own separate <asp:ImageField column, without using template fields. However, template columns give us more control over layout, and are often easier to work with.