Using Template Fields With The GridView Control In ASP.NET
November 22, 2009 by Matthew Fletcher
Filed under Computers
Adding a GridView control to an ASP.NET page is one of the simplest ways of displaying databound data. The GridView can be created simply by opening the Database Explorer and dragging the table or view that from which you want to display information. However, the default GridView which is automatically generated in this way almost always needs some tweaking. One typical change you may want to make is to change some of the BoundFields elements to TemplateFields elements.
The BoundField object displays data from a given column in the data source with no real modification. By contrast, any content you desire can be placed inside a TemplateField element. This makes it ideal for setting up validation through the use of validation controls.
TemplateFields offer great flexibility by allowing you to include a variety of templates to cater for the different states of the conditions arising within the GridView. There are several types of template which may be added inside a TemplateField object; the main ones are described below.
Use the HeaderTemplate to customize the information which will be displayed in the header of the column in which the TemplateField is located.
The ItemTemplate is used to display the information which you want displayed for each row of data when the GridView object is not selected for editing.
Use the EditItemTemplate to hold the information which you want displayed for each row of data when the GridView object is in edit mode. It is here that you would place the controls necessary for validation.
Most of the time, information currently held in the database is displayed by adding a TextBox control inside the EditItemTemplate and databind it to the appropriate column from the data source using a statement like Bind(“FirstName”). Inside the same EditItemTemplate, you would then place the necessary validation control. For example, if you want to ensure that the field is not left blank when the form is submitted, you would insert a RequiredFieldValidator control.
Author is a developer and trainer with Macresource Computer Training, a UK IT training company offering ASP.NET Classes in London and throughout the UK.











