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]">
</asp:SqlDataSource>
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
[![ChooseDataSource](https://msdntnarchive.z22.web.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/webdevelopertips/WindowsLiveWriter/Tip64DidyouknowHowtoconvertaGridViewcolu_8EB0/ChooseDataSource_thumb.jpg "ChooseDataSource")](https://msdntnarchive.z22.web.core.windows.net/media/TNBlogsFS/BlogFileStorage/blogs_msdn/webdevelopertips/WindowsLiveWriter/Tip64DidyouknowHowtoconvertaGridViewcolu_8EB0/ChooseDataSource.jpg) <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
</Columns>
</asp:GridView>
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">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Email") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
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
Comments
Anonymous
May 27, 2009
PingBack from http://asp-net-hosting.simplynetdev.com/tip64did-you-know-%e2%80%a6-how-to-convert-a-gridview-column-from-aspboundfield-to-asptemplatefield-in-design-view/Anonymous
May 28, 2009
Assume that you already have a data source SqlDataSource1 that binds to a simple query returning someAnonymous
May 29, 2009
Thank you for submitting this cool story - Trackback from DotNetShoutout