最近項目是在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