asp.net2.0数据邦定
最近项目是在dnn下开发模块,遇到几则数据绑定的应用,贴出来:
<tr runat="server" visible='<%# Eval("Description").ToString()<>"" %>'>
<td style="width: 240px; border-bottom: #efefef 2px dashed; font-weight: bolder;" valign="top">
Description</td>
<td style="width: 800px; border-bottom: #efefef 2px dashed">
<asp:Label runat="server" ID="Summary_bolder" style="font-weight: bolder" Visible='<%# Eval("Description").ToString()<>"" %>' >Summary:<br/></asp:Label>
<asp:Label runat="server" ID="Label_nbsp1" Visible='<%# Eval("Description").ToString()<>"" %>' > </asp:Label><asp:Label ID="DescriptionLabel" runat="server" Text='<%# Eval("Description") & "<br/><br/>" %>' Visible='<%# Eval("Description").ToString()<>"" %>' ></asp:Label>
<asp:Label runat="server" ID="ExtendedDescription_bolder" style="font-weight: bolder" Visible='<%# Eval("Extended_Description").ToString()<>"" %>' >Extended Description:<br/></asp:Label>
<asp:Label runat="server" ID="Label_nbsp2" Visible='<%# Eval("Extended_Description").ToString()<>"" %>' > </asp:Label><asp:Label ID="Extended_Description" runat="server" Text='<%# Eval("Extended_Description") %>' Visible='<%# Eval("Extended_Description").ToString()<>"" %>' ></asp:Label>
</td>
</tr>
解释一下:
1。第一行tr的visible属性是控制如果数据库某个字段(此例是:Description)为空,则table的某行就不显示!注意:前台的数据绑定时是语法相关的,VB.NET和cs.net是不同的,如页面用C#,则区分大小写,且方法需要“()”,而vb的ToString函数是可以不要“()”。下面其他的visible控制显示与否基本类似!
2。注意DescriptionLabel的绑定后面还加上了两个回车,此时只能单向绑定(Eval),而不能双向绑定(Bind)!
3。另:再看看Scott的绑定,如果您的绑定的逻辑比较复杂,可以写后台逻辑的:
<asp:TemplateField HeaderText="Days On The Job">
<ItemTemplate>
<%# DisplayDaysOnJob((Northwind.EmployeesRow) ((System.Data.DataRowView) Container.DataItem).Row) %>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
后台的DisplayDaysOnJob的方法是:
protected string DisplayDaysOnJob(Northwind.EmployeesRow employee)
{
// 确保HiredDate不为空……如果为空的话,返回“Unknown”
if (employee.IsHireDateNull())
return "Unknown";
else
{
// 返回当前日期/时间与HireDate之间所隔的天数
TimeSpan ts = DateTime.Now.Subtract(employee.HireDate);
return ts.Days.ToString("#,##0");
}
}
这样数据绑定我们就可以随意写了!
此教程是Scott Mitchell 的ASP.NET 2.0数据教程之十二:在GridView控件中使用TemplateField


浙公网安备 33010602011771号