Tip#64:Did you know … How to convert a GridView column from asp:BoundField to asp:TemplateField in Design View?

Assume that you already have a data source SqlDataSource1 that binds to a simple query returning some details from the Customers table.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:MyConnectionString %>" 
    SelectCommand="SELECT [FirstName], [LastName], [Email] FROM [Customers] ORDER BY [FirstName]">

In Visual Studio, if you add a GridView control to a web forms page in Design View and choose SqlDataSource1 as the Data Source (as shown in figure 1 below), typically the GridView columns are generated as asp:BoundField types in source.

Figure 1


        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                <asp:BoundField DataField="FirstName" HeaderText="FirstName" 
                    SortExpression="FirstName" />
                <asp:BoundField DataField="LastName" HeaderText="LastName" 
                    SortExpression="LastName" />
                <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />

Often, you want to customize one or more columns by converting them into an asp:TemplateField rather than asp:BoundField. Let’s say you want to convert the Email column into a asp:TemplateField.

You can quickly do this in Design View by clicking on ‘Edit Columns’ in the Smart Tasks panel of the GridView, select the ‘Email’ field in the dialog that pops up and click on ‘Convert this field into a TemplateField’, then click ‘OK’.

Figure 2


Figure 3


The source for the field Email will now be updated to:

<asp:TemplateField HeaderText="Email" SortExpression="Email">
        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("Email") %>'></asp:Label>

You can also do a similar thing with the DetailsView control by choosing the ‘Edit Fields’ item in the Smart Tasks panel of the DetailsView control.


Bala Chirtsabesan

SDET | Visual Web Developer