我正在尝试将网格视图绑定到可折叠面板扩展器主体的转发器中。这是代码:
<!-- Collapsible panel extender body -->
<asp:Panel ID="pBody1" runat="server" CssClass="cpBody">
<asp:Label ID="lblBodyText1" runat="server" />
<asp:Repeater ID="Repeater2" runat="server" OnItemDataBound="Repeater2_ItemDataBound">
<ItemTemplate>
<asp:GridView ID="gvProduct" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="categoryName" HeaderText="Category" />
<asp:BoundField DataField="inventoryQuantity" HeaderText="Quantity" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:Repeater>
</asp:Panel>
从后面的代码中,我试图通过列表循环获取类别名称。然后,我根据类别名称获取所有产品并将其显示在gridview中。
protected void Repeater2_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// This event is raised for the header, the footer, separators, and items.
//Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
for (int count = 0; count < categoryList.Count; count++)
{
string category = categoryList[count].categoryName;
List<ProductPacking> prodList = new List<ProductPacking>();
prodList = packBLL.getAllProductByCategory(category);
gvProduct.DataSource = prodList;
gvProduct.DataBind();
}
}
}
然而,它告诉我gvProduct在当前上下文中不存在。我想知道如何在转发器中获得组件?或者我的做法是错误的?
更新了部分。
这是我绑定类别名称的标头的方法。我正在使用另一个中继器:
<asp:Label ID="lblCategory" Text='<%# DataBinder.Eval(Container.DataItem, "categoryName") %>' runat="server" />
从后面的代码中,在页面加载时,我得到了所有类别:
if (!IsPostBack)
{
//Get all category and bind to repeater to loop
categoryList = packBLL.getAllCategory();
Repeater1.DataSource = categoryList;
Repeater1.DataBind();
}
对于在每个类别中显示产品的repeater2,我将其编辑为:
protected void Repeater2_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// This event is raised for the header, the footer, separators, and items.
string category = e.Item.FindControl("categoryName").ToString();
//Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
GridView gv = (GridView)e.Item.FindControl("gvProduct");
if (gv != null)
{
List<ProductPacking> prodList = new List<ProductPacking>();
prodList = packBLL.getAllProductByCategory(category);
DataRowView drv = (DataRowView)e.Item.DataItem;
gv.DataSource = prodList;
gv.DataBind();
}
}
}
然而,当我展开扩展器时,没有任何东西出现。
答案 0 :(得分:0)
如果我没记错,您需要使用FindControl
来访问属于模板的控件,例如
GridView oGV = e.Item.FindControl ( "gvProducts" ) as GridView;
您不能将GridView称为gvProducts
,因为没有具有该名称的单个GridView控件 - 为模板中的每个数据项创建不同的实例(具有不同的名称)。您需要当前行的实例。
这是一个MSDN example,展示了如何在数据绑定期间访问控件(该示例使用Label
)。