ASP的ListView:如何访问一个数据绑定到行中的数据? [英] ASP ListView: How do I access the data that is databound to the rows?
问题描述
我要访问处理列表视图事件,例如,当被数据绑定到我的列表视图中的数据:
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)
或
protected void List_ItemCommand(object sender, ListViewCommandEventArgs e)
事件里面,我无法访问通过财产以后的数据,如评估(ID)
目前我们使用的是非常哈克解决方案:
Currently we are using a very hacky solution:
string id = e.Item.FindControl("lblID").Text;
其中, lblID
是填充用的aspx文件数据隐藏控件:
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?
推荐答案
一些调整,我发现了妥善解决后:
After a bit of tinkering I found the proper solution:
数据密钥需要被添加到列表视图。数据键不像一个数据绑定到一个列表视图中的数据持久化。要设置数据的关键只是在ListView标签中指定的名称:
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:
<asp:ListView ID="MyListview" runat="server" DataKeyNames="ID" ......
然后从事件访问键:
Then to access the keys from the event:
protected void MyListView_ItemCommand(object sender, ListViewItemEventArgs e)
{
// Get the item index of the Item
int itemIndex = ((ListViewDataItem)e.Item).DisplayIndex;
// Extract the key and cast it to its data type.
DataKey key = ((ListView)sender).DataKeys[itemIndex];
int myId = (int) key;
// Use ID to delete / modify the item in the SQL database....
}
这篇关于ASP的ListView:如何访问一个数据绑定到行中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!