Robert
Robert

Reputation: 38213

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)

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?

Upvotes: 1

Views: 4593

Answers (3)

Caph
Caph

Reputation: 11

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:-

(ActualDataType)(((ListViewDataItem)e.Item).DataItem)

Upvotes: 1

Robert
Robert

Reputation: 38213

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

Upvotes: 1

Graham Clark
Graham Clark

Reputation: 12966

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.

Upvotes: 1

Related Questions