web developer tips (64): 在GridView中转换BoundField为TemplateField
原文地址:How to convert a GridView column from asp:BoundField to asp:TemplateField in Design View
假定你有个数据源SqlDataSource1 ,绑定了一个简单的查询语句,返回Customers表的详细信息。
http://www.watch-life.net/visual-studio/convert-a-gridview-column-from-boundfield-to-templatefield.html
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT [FirstName], [LastName], [Email] FROM [Customers] ORDER BY
[FirstName]">
</asp:SqlDataSource>
在Visual Studio里,在web forms 页面的设计视图添加一个GridView,选择 SqlDataSource1作为数据源,通常GridView 列会生成 BoundField型数据
<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>
通常,你想自定义一列或多列从BoundField转换到TemplateField,这里我们把Email列转换成TemplateField。在GridView的智能标签面板里单击“Edit Columns”。然后在弹出的对话框选择“Email”字段,并单击“Convert this field into a TemplateField”
Email 字段的代码会进行更新,如下所示:
<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>
对于DetailsView控件,也可以参照类似的方法去做,在DetailsView的智能标签面板选择“Edit Fields”即可。
更多文章见:守望轩[http://www.watch-life.net/]