Many Databinding settings can be expressed declaratively.
- Example - Setting a HyperLink "Text" and "NavigateURL" properties declaratively:
<asp:HyperLink runat="server" ID="categoryHyperLink"
Text='<%#String.Format("{0} ({1})", Eval("CategoryName"), Eval("TotalProducts")) %>'
NavigateUrl='<%# "~/SomeURL.aspx?id=" + Eval("CategoryID") %>' />This would result in a link like "Vegetables (4)", whose URL would pass the "CategoryID" has the querystring "id" parameter.
- In some more complex situations a call to a method can be used, for example the "Text" propertie from the example above could be replaced with:
Text='<%# getCategoryWithTotalProducts((string)Eval("CategoryName"),
(int)Eval("NumberOfProducts"))%>'where getCategoryWithTotalProducts method would be defined in the code behind:
protected string getCategoryWithTotalProducts(string categoryName, int totalProducts)
{
return String.Format("{0} ({1})", categoryName, totalProducts);
}Many ASP.NET Web Controls have two distinct DataSource properties, and only one can be set at a given time:
- DataSource: can be set directly to a an object like a DataTable;
- DataSourceID: can be set to a DataSource Control ID like an "ObjectDataSource", an "SQLDataSource", etc.;
- Example using the DataSource property on a Repeater Web Control (set on code-behind):
<asp:Repeater ID="CategoriesRepeater" runat="server" >
<HeaderTemplate><ul></HeaderTemplate>
<FooterTemplate></ul></FooterTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="categoryHyperLink"
Text='<%#String.Format("{0} ({1})", Eval("CategoryName"), Eval("NumberOfProducts")) %>'
NavigateUrl='<%# "~/DataListRepeaterBasics/CategoriesAndProducts2.aspx?id=" + Eval("CategoryID") %>' />
</li>
</ItemTemplate>
</asp:Repeater>The cs file:
protected void Page_Load(object sender, EventArgs e)
{
CategoriesRepeater.DataSource = getCategories();
CategoriesRepeater.DataBind();
}
protected Northwind.CategoriesDataTable getCategories()
{
CategoriesBLL categoriesAPI = new CategoriesBLL();
return categoriesAPI.GetCategoriesAndNumberOfProducts();
}The DataBind() method must be called after setting the DataSource property to actually bind the data to the Web Control.
- Example using the DataSourceID property to an ObjectDataSource (set declaratively):
<asp:Repeater ID="CategoriesRepeater" runat="server"
DataSourceID="CategoryDataSource">
<HeaderTemplate><ul></HeaderTemplate>
<FooterTemplate></ul></FooterTemplate>
<ItemTemplate>
<li>
<asp:HyperLink runat="server" ID="categoryHyperLink"
Text='<%#String.Format("{0} ({1})", Eval("CategoryName"), Eval("NumberOfProducts")) %>'
NavigateUrl='<%# "~/DataListRepeaterBasics/CategoriesAndProducts2.aspx?id=" + Eval("CategoryID") %>' />
</li>
</ItemTemplate>
</asp:Repeater>
<asp:ObjectDataSource ID="CategoryDataSource" runat="server"
OldValuesParameterFormatString="original_{0}"
SelectMethod="GetCategoriesAndNumberOfProducts" TypeName="CategoriesBLL">
</asp:ObjectDataSource>
No comments:
Post a Comment