天天看點

模闆和資料綁定表達式

幾乎所有的資料綁定控件都支援模闆(template)。

在顯示資料時,可以用模闆來格式化每個資料項的布局和外觀。

通過模闆,可以使用資料綁定表達式來顯示資料項的值。

使用模闆

(除TreeView外)2.0中的資料綁定控件都支援模闆。

Repeater、DataList、FormView必須使用模闆顯示資料。

GridView、DetailsView、Menu等支援模闆,但不是必須使用。

模闆中可以包含

  • HTML
  • 資料綁定表達式
  • 其他控件

示例:超連結清單

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>顯示連結</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Repeater ID="Repeater1" runat="server" DataSourceID="srcMovies">
        <ItemTemplate>
            <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#eval("id","details.aspx?id={0}") %>'> <%#Eval("title") %> </asp:HyperLink>
            <br/>
        </ItemTemplate>
        </asp:Repeater>
    
        <asp:SqlDataSource ID="srcMovies"
        ConnectionString="data source=.\sqlexpress;integrated security=true;user instance=true;attachdbfilename=|datadirectory|mydatabase.mdf"
        SelectCommand="select id,title from movies"
        runat="server" />
    </div>
    </form>
</body>
</html>      
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="gv1" DataSourceID="srcMovies" runat="server">
    </asp:GridView>    
    
    <asp:SqlDataSource ID="srcMovies"
    ConnectionString="data source=.\sqlexpress;integrated security=true;user instance=true;attachdbfilename=|datadirectory|mydatabase.mdf"
    SelectCommand="select title,director from movies where [email protected]"
    runat="server" >
        <SelectParameters>
            <asp:QueryStringParameter Name="mid" Type="Int32" QueryStringField="id" />
        </SelectParameters>
    </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>      

使用資料綁定表達式

資料綁定表達式,直到運作時才計算出結果。

(在頁面中使用)隻要将表達式包含在<%# %>符号中。

資料綁定表達式在控件的DataBinding事件觸發時才開始計算值。

對于【聲明式資料綁定】這個事件是自動觸發的。

對于【程式設計式資料綁定】事件在調用DataBind方法時觸發。