1. 创建一个用户控件。
namespace Northwind.WebSite.UserControls
{
public partial class CategoryDetail : System.Web.UI.UserControl
{
private Category category;
public Category Category
{
set { category = value; }
get { return category; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreRender(object sender, EventArgs e)
{
GridViewProducts.DataSource = category.Products;
GridViewProducts.DataBind();
LableCategoryName.Text = category.CategoryName;
LabelTotalPrice.Text = string.Format("Total price: {0}",
category.Products.Sum(p =>
p.UnitPrice * (p.UnitsInStock + p.UnitsOnOrder)));
}
public void ExpandCollapsiblePanel()
{
CollapsiblePanelExtender1.Collapsed = false;
}
}
}
2. 实现ITemplate。
namespace Northwind.WebSite.TemplateControl
{
public class CategoryDetailTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
CategoryDetail detail = (CategoryDetail)BuildManager.
CreateInstanceFromVirtualPath("~/UserControls/CategoryDetail.ascx", typeof(CategoryDetail));
container.DataBinding += delegate(object sender, EventArgs e)
{
IDataItemContainer container1 = container as IDataItemContainer;
detail.Category = (Category)container1.DataItem;
if (container1.DataItemIndex == 0)
{
detail.ExpandCollapsiblePanel();
}
};
container.Controls.Add(detail);
}
}
}
3. 动态加载。
namespace Northwind.WebSite
{
public partial class ProductsByCategory : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Repeater1.ItemTemplate = new CategoryDetailTemplate();
if (!IsPostBack)
{
var ds = Category.GetCategories();
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
}
}
}

0 Comments.