如何在转发器的按钮单击事件处理程序中获取绑定对象?
我有一个中继器,并将一个对象列表绑定到它,如下所示:
List<MyClass> myList = //....
MyRepeater.DataSource = myList;
MyRepeater.DataBind();
在中继器内部,我有一个由该处理程序处理的链接按钮:
protected void Button_ItemCommand(object source, RepeaterCommandEventArgs e) {
if (e.CommandName == "Edit") {
// I need to get my listItem.Id here
}
}
它应该很容易,但我找不到如何做到这一点。
谢谢。
I have a repeater and bind a list of objects to it, like this:
List<MyClass> myList = //....
MyRepeater.DataSource = myList;
MyRepeater.DataBind();
Inside the repeater I have a link button which is handled by this handler:
protected void Button_ItemCommand(object source, RepeaterCommandEventArgs e) {
if (e.CommandName == "Edit") {
// I need to get my listItem.Id here
}
}
It should be easy but I can't find how to do it.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想要单击的实际链接按钮,该按钮已在
对象源
参数中传递给此方法,只需对其进行适当的转换即可。如果您想要中继器中的其他控件,您可以使用
EDIT
如果您想要此行绑定到的对象的属性,这将是一个痛苦的事情,而且会很难看。您需要在会话或视图状态中跨回发保留转发器绑定到的数据源。完成此操作后,您可以通过将其索引与单击的中继器行的索引相匹配来访问源中适当的对象,您可以通过以下方式获取该对象:
请注意,最简单的方法是将此值存储在某处在你的中继器中。
If you want the actual link button that was clicked, that's already being passed to this method in the
object source
parameter—just cast it appropriately.If you want some other control that's in your repeater, you can use
EDIT
If you want a property from the object this row is bound to, this will be a pain to do, and it'll be ugly. You'll need to persist the DataSource the repeater is bound to across postbacks, either in Session or ViewState. Once you do that, you can access the appropriate object in the source by matching its index with the index of the reeater's row that was clicked, which you can get by:
Note that the easiest way is to just store this value somewhere in your repeater.
大多数时候,从存储/缓存/等中获取绑定对象很容易。如果您有身份证件。既然您在问题中说“
我需要在此处获取我的 listItem.Id
”,我认为您不介意重新获取对象本身,而只是寻找一种仅获取标识符的方法从中继器。只需给按钮一个命令参数,如下所示:
然后就像您在问题中正确所说的那样,
Most of the time it's easy to fetch the bound object from your storage/cache/etc. if you have the ID. Since you said in your question "
I need to get my listItem.Id here
", I think you don't mind re-fetching the object itself and are just looking for a way to get only the identifier from the repeater.Just give the button a command argument as shown:
Then like you rightly said in your question,
你不能这样做。 ASP.Net 不会在回发过程中保留原始数据绑定对象。您必须将要保留的数据存储在中继器内的控件中。然后您可以通过 EventArgs 访问该控件,例如
You cannot do this. The original databound object is not persisted by ASP.Net across postbacks. You have to store the data you want to keep in a control inside the repeater. You can then access the control via the EventArgs, e.g.