如何通过中继器将项目绑定到控件?
我在转发器内部有“BasketControl”控件:
<asp:Repeater runat="server" ID="rptItems">
<ItemTemplate>
<uc:BasketControl runat="server" ID="ucBasket" />
</ItemTemplate>
</asp:Repeater>
BasketObject 列表绑定了转发器 DataSource 属性。
public class MyParentControl : System.Web.UI.UserControl
{
void Page_Load(object sender, EventArgs e) {
if(!IsPostback) {
rptItems.DataSource = ...; // List<BasketObject>
rptItems.DataBind();
}
}
}
如何访问 BasketControl 内的“BasketObject”? 我想要的是访问 BasketControl 类内部的 BasketObject,例如“Page_Load”方法内部。
public class BasketControl : System.Web.UI.UserControl
{
void Page_Load(object sender, EventArgs e) {
// here I want access BasketObject
BasketObject basket = .... as BasketObject;
}
}
应该很简单,但在 Google 中找不到任何提示...
PS 我应该处理“OnItemDataBound”重复器事件并将数据对象分配给控件吗?或者有更快/更简单的方法吗?
谢谢
I have 'BasketControl' control inside of repeater:
<asp:Repeater runat="server" ID="rptItems">
<ItemTemplate>
<uc:BasketControl runat="server" ID="ucBasket" />
</ItemTemplate>
</asp:Repeater>
The list of BasketObject is bound the repeater DataSource property.
public class MyParentControl : System.Web.UI.UserControl
{
void Page_Load(object sender, EventArgs e) {
if(!IsPostback) {
rptItems.DataSource = ...; // List<BasketObject>
rptItems.DataBind();
}
}
}
How can I access 'BasketObject' inside of BasketControl?
What I want is to have access to BasketObject inside of class BasketControl, for example inside of the 'Page_Load' method.
public class BasketControl : System.Web.UI.UserControl
{
void Page_Load(object sender, EventArgs e) {
// here I want access BasketObject
BasketObject basket = .... as BasketObject;
}
}
Should be simple, but can't find any tips in Google...
P.S. Should I handle 'OnItemDataBound' repeater event and assign data object to control? Or there is quicker/easier way?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常我处理此类事情的方式是处理
ItemDatabound
事件。假设您有这样的标记:
代码看起来像这样:
希望这是清楚的。当然,您也可以使用 AutoEventWireup="true" 并将事件处理程序的名称放入 Repeater 的标记中。但基本思想仍然是一样的。
编辑为了回应您的澄清,您将必须明确地以某种方式连接它们。没有一种自动的方法可以做到这一点。
我建议在
BasketControl
上公开一个Basket
属性。然后您可以执行以下操作:并且您不需要处理
ItemDatabound
事件。如果有另一种方法可以做到这一点,我不确定它是什么。Usually how I handle those kind of things is by handling the
ItemDatabound
event.So say you have this markup:
The code would look something like this:
Hope that's clear. Of course, you could also use
AutoEventWireup="true"
and put the name of the event handler in the markup of the Repeater. But the basic idea is still the same.EDIT In response to your clarification, you're going to have to explicitly wire them up some how. There isn't an automatic way of doing it.
I would suggest exposing a
Basket
property on theBasketControl
. Then you could do something like this:And you wouldn't need to handle the
ItemDatabound
event. If there's another way of doing this, I'm not sure what it is.