Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data being bound to ListView on DataBound event

I have a ListView control and I have added a DataBound event (don't know if this is the correct one) to the control.

I'm wanting to access the data being bound to that particular ItemTemplate from this event, is that possible?

like image 251
Fermin Avatar asked May 13 '09 13:05

Fermin


2 Answers

C# Solution

protected void listView_ItemDataBound(object sender, ListViewItemEventArgs e)
{        
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        ListViewDataItem dataItem = (ListViewDataItem)e.Item;
        // you would use your actual data item type here, not "object"
        object o = (object)dataItem.DataItem; 
    }
}

Why they made this so different for ListView still sort of puzzles me. There must be a reason though.

like image 126
Adam Nofsinger Avatar answered Nov 10 '22 00:11

Adam Nofsinger


A little late, but I'll try to answer your question, as I had the same problem and found a solution. You have to cast Item property of the ListViewItemEventArgs to a ListViewDataItem, and then you can access the DataItem property of that object, like this:

Private Sub listView_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles productsList.ItemDataBound
    If e.Item.ItemType = ListViewItemType.DataItem Then
        Dim dataItem As Object = DirectCast(e.Item, ListViewDataItem).DataItem
    ...
End Sub

You could then cast the dataItem object to whatever type your bound object was. This is different from how other databound controls like the repeater work, where the DataItem is a property on the event args for the DataBound method.

like image 34
KOTJMF Avatar answered Nov 09 '22 23:11

KOTJMF