views:

24

answers:

2

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?

+1  A: 

In your event handlers, use the EventArgs object.

e.Item.DataItem

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 and CommandArgument properties of the LinkButton (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.

Graham Clark
I do not have e.Item.DataItem, It doesn't appear on intellisense and causes an error when I try and compile it.
Robert
@Robert - you may not get it on the ItemCommand event, but you should have it in the ItemDataBound event - this is what the MSDN page I linked to shows. Is this not the case?
Graham Clark
Nope, can't get it on any of the events. I have found a workaround solution that works for the ItemDataBound method, but im still having problems with the ItemCommand method. I think the problem might be that I'm using a DataSource instead of an ObjectDataSource.
Robert
A: 

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:

<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....
}
Robert