TemplateField 控件的使用

 1、基本

  1. <asp:TemplateField HeaderText="Price"  SortExpression="UnitPrice"
  2.   ItemStyle-Font-Bold="True">
  3.   <ItemTemplate>
  4.     <asp:Label runat="server"
  5.       Text='<%# Eval("UnitPrice", "${0:F2}") %>' />
  6.   </ItemTemplate>
  7.   <EditItemTemplate>
  8.     <asp:TextBox ID="UnitPrice" runat="server"
  9.       Text='<%#Bind("UnitPrice")%>' />
  10.     <asp:RequiredFieldValidator ID="rfv1" runat="server"
  11.       ControlToValidate="UnitPrice"
  12.       Text="You must enter the price" />
  13.   </EditItemTemplate>
  14. </asp:TemplateField>

Eval和Bind这两个方法之间的区别在于,Eval提供了只读绑定,而Bind提供了读写绑定,通常会在不同模板中使用这两个方法。可以体会上面的代码。

 

2、与DropDownList 联合

  1. <asp:TemplateField HeaderText="Supplier">
  2.   <ItemTemplate>
  3.     <%#Eval("CompanyName") %>
  4.   </ItemTemplate>
  5.   <EditItemTemplate>
  6.     <asp:SqlDataSource ID="Sds1" runat="server"
  7.      ConnectionString="<%$ConnectionStrings:NorthwindConnectString%>"
  8.       SelectCommand="SELECT SupplierID, CompanyName
  9.                      FROM Suppliers ORDER BY CompanyName" />
  10.     <asp:DropDownList ID="SupplierID" runat="server"
  11.       DataSourceId="Sds1"
  12.       DataValueField="SupplierID" DataTextField="CompanyName"
  13.       SelectedValue='<%#Bind("SupplierID")%>' />
  14.   </EditItemTemplate>
  15. </asp:TemplateField>

可以看到,ItemTemplate 只是显示CompanyName,而EditItemTemplate包含一个SqlDataSource和一个DropDownList。数据源获取所有供应商的ID和名字,列表绑定到这个数据。DataValueField放置ID,DataTextField放置显示数据。这里的关键是SelectedValue,它设置为一个数据绑定表达式,在此使用Bind来提供与SupplierID列的双向绑定。因为使用了SelectedValue,底层行SupplierID会显示为列表中的当前所选项,另外由于使用了Bind,点击UpDate链接时。会通过数据源控件将新的SupplierID放回数据库。

参考:

ASP.NET 2.0 Illustrated     (英)Alex Homer;Dave Sussman

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值