If you need to access DataKeys of a ListView from inside the ItemDataBound you need to use the ListViewDataItem class. The ListViewDataItem class represents an individual data item in the ListView control. Every data item refers to a record in the data source.
The trick is to use the ListViewDataItem.DisplayIndex property! This property returns the index of the currently bound row inside the ListView collection of items.
A sample code could help more:
protected void PostList_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// Get the listview
ListView listView = (ListView)sender;
//Get the item object.
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
// Only data items are allowed
if (e.Item.ItemType != ListViewItemType.DataItem) return;
// Get the PostID from the ListView's datakey
int postID = int.Parse(listView.DataKeys[dataItem.DisplayIndex].Value.ToString());
}
The ListView DataKeyNames had a value of "PostID" which represents the primary key column in the data table.
First of all you cast the e.Item property to an instance of ListViewDataItem, then using the DisplayIndex property you can access the DataKeys of the currently bound row!
Hope this helps,
Regards
Tags: