在模板化控件中綁定到數(shù)據(jù)
FormView、DataList、Repeater 和 ListView Web 服務(wù)器控件使用模板顯示數(shù)據(jù)和檢索用戶輸入,以插入、更新或刪除數(shù)據(jù)。此外,您還可以將模板與 GridView 和 DetailsView 控件一同使用,以自定義數(shù)據(jù)布局。
通過將模板化控件的 DataSourceID 屬性設(shè)置為數(shù)據(jù)源控件的 ID,可以將模板化控件綁定到數(shù)據(jù)源控件(例如 LinqDataSource、ObjectDataSource 或 SqlDataSource 控件)。然后可以在模板中使用 Eval 和 Bind 函數(shù)綁定到數(shù)據(jù)源中的數(shù)據(jù)。有關(guān)更多信息,請(qǐng)參見 數(shù)據(jù)綁定表達(dá)式語法。
使用模板將控件綁定到數(shù)據(jù)
1.向頁添加數(shù)據(jù)源控件(如 SqlDataSource 控件),如下面的示例所示:
<asp:SqlDataSource ID="SqlDataSource1" SelectCommand="SELECT * FROM [Products]" ConnectionString="<%$ ConnectionStrings:NorthwindConnection %>" RunAt="server"></asp:SqlDataSource>
2.添加一個(gè)支持模板的控件,如 ASP.NET FormView 控件。
3.將模板化控件的 DataSourceID 屬性設(shè)置為步驟 1 中數(shù)據(jù)源控件的 ID,如此示例中所示:
<asp:FormView ID="FormView1" DataSourceID="SqlDataSource1" DataKeyNames="ProductID" Runat="server"></asp:FormView>
4.向模板化控件添加模板并使用控件和標(biāo)記填充這些模板。
5.若要顯示數(shù)據(jù),請(qǐng)將 Eval 函數(shù)作為屬性設(shè)置使用,并引用綁定數(shù)據(jù)字段。在用于插入或編輯數(shù)據(jù)的模板中,使用 Bind 函數(shù)引用數(shù)據(jù)綁定字段,如以下示例所示:
<asp:FormView ID="FormView1" DataSourceID="SqlDataSource1" DataKeyNames="ProductID" RunAt="server"> <ItemTemplate> <table> <tr><td align="right"><b>Product ID:</b></td> <td><%# Eval("ProductID") %></td></tr> <tr><td align="right"><b>Product Name:</b></td> <td><%# Eval("ProductName") %></td></tr> <tr><td align="right"><b>Category ID:</b></td> <td><%# Eval("CategoryID") %></td></tr> <tr><td align="right"><b>Quantity Per Unit:</b></td><td><%# Eval("QuantityPerUnit") %></td></tr> <tr><td align="right"><b>Unit Price:</b></td> <td><%# Eval("UnitPrice") %></td></tr> </table> </ItemTemplate> </asp:FormView>
每個(gè) Web 服務(wù)器控件支持不同的模板。例如,Repeater 控件支持一個(gè) ItemTemplate 和一個(gè) AlternatingItemTemplate,以使用交替控件、樣式和標(biāo)記來顯示數(shù)據(jù)。
綁定到Visual Studio的模板化控件中的數(shù)據(jù)
可以將一個(gè)控件(例如 GridView、DetailsView、FormView、ListView、DataList 或 Repeater 控件)與一個(gè)數(shù)據(jù)源控件(例如 LinqDataSource、ObjectDataSource 或 SqlDataSource 控件)關(guān)聯(lián)起來。此外還可以使用控件的模板(ListView、DataList、Repeater 和 FormView 控件需要模板)在設(shè)計(jì)器中通過自定義用戶界面 (UI) 來自定義數(shù)據(jù)表示形式。
此主題演示如何將用戶界面控件(如 TextBox 控件)添加到模板中并將該控件綁定到特定數(shù)據(jù)。
將模板控件綁定到數(shù)據(jù)源
1.在頁上建立有效的數(shù)據(jù)源(如 SqlDataSource 控件),并注意 ID 屬性值。
例如:
<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT CustomerID, CompanyName FROM Customers" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"></asp:SqlDataSource>
<asp:DataList ID="DataList1" runat="server" DataKeyField="CustomerID" DataSourceID="SqlDataSource1"> <ItemTemplate> CustomerID: <asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Eval("CustomerID") %>'> </asp:Label><br /> CompanyName: <asp:Label ID="CompanyNameLabel" runat="server" Text='<%# Eval("CompanyName") %>'> </asp:Label><br /> <br /> </ItemTemplate></asp:DataList>
|
新聞熱點(diǎn)
疑難解答
圖片精選