ASP ListView:如何访问数据绑定到行的数据?
我想在处理列表视图事件时访问数据绑定到列表视图的数据,例如:
protected void List_ItemDataBound(object sender, ListViewItemEventArgs e)
或
protected void List_ItemCommand(object sender, ListViewCommandEventArgs e)
在事件内部,我无法通过诸如 Eval("ID")
之类的东西访问数据
目前我们正在使用一个非常hacky的解决方案:
string id = e.Item.FindControl("lblID").Text;
其中lblID
是一个隐藏控件,它使用aspx文件中的数据填充:
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' />
当我看到这个时,我的眼睛流血了,有更好的方法吗?
I want to access the data that was databound to my list view when handling list view events such as:
protected void List_ItemDataBound(object sender, ListViewItemEventArgs e)
or
protected void List_ItemCommand(object sender, ListViewCommandEventArgs e)
Inside the events, I can not access the data via somthing like Eval("ID")
Currently we are using a very hacky solution:
string id = e.Item.FindControl("lblID").Text;
Where lblID
is a hidden control that is populated with data in the aspx file using:
<asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' />
My eyes bleed when I look at this, Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在事件处理程序中,使用 EventArgs 对象。
会给你你正在寻找的物体;然后你只需要把它转换成你需要的类型。
此 MSDN 页面一个更完整的例子。
对于 ItemCommand 事件处理程序,您可能没有此选项。在本例中,我将使用
LinkButton
(或您正在使用的任何内容)的CommandName
和CommandArgument
属性。将您的 ID 作为 CommandArgument,然后您可以从事件处理程序中的事件参数对象中选取它。In your event handlers, use the EventArgs object.
will give you the object you're looking for; you then just need to cast it to the type you need.
This MSDN page has a fuller example.
For the ItemCommand event handler, you may not have this option. In this case, I would use the
CommandName
andCommandArgument
properties of theLinkButton
(or whatever you're using). Put your ID as the CommandArgument, you can then pick this up from the event argument object in the event handler.经过一番修补后,我找到了正确的解决方案:
需要将数据键添加到列表视图中。与数据绑定到列表视图的数据不同,数据键是持久的。要设置数据键,只需在 ListView 标记中指定名称:
然后从事件访问键:
After a bit of tinkering I found the proper solution:
Data keys need to be added to the list view. Data keys are persistent unlike the data that is databound to a listview. To set the data key just specify the name in the ListView tag:
Then to access the keys from the event:
只是为了扩展您提到的 ItemDataBoundEvent 解决方案,您不需要通过 ListView 的 DataKeys 来访问 ItemDataBoundEvent 中的数据。将 e.Item 转换为 ListViewDataItem 使您可以访问 DataItem 属性,然后可以将其转换为基础数据类型,从而使您可以智能感知访问每个基础数据字段。例子:-
Just to expand on the ItemDataBoundEvent solution you alluded to, you don't need to go via the ListView's DataKeys to access the data in the ItemDataBoundEvent. Casting e.Item to ListViewDataItem gives you access to the DataItem property which you can then cast to the underlying data type, giving you intellisense access to every underlying data field. Example:-