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?


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.

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.

Found a workaround, I created a method to format the data how I needed and called it from the markup using:

<%# doFormatting(Convert.ToInt32(Eval("Points")))%>

The data that is used for the current item can be found from the EventArgs.

So from the RepeaterItemEventArgs e we can access the current item by looking in e.Item.DataItem.

protected void listView_ItemDataBound(object sender, ListViewItemEventArgs e)
    if (e.Item.ItemType == ListViewItemType.DataItem)
        var currentItem = e.Item.DataItem;


 ? Formatting DataBinder.Eval data
 ? DataBinder.Eval in c#
 ? Binding to a List<string> using DataBinder.Eval
 ? C# - Looping trough a Repeater control and accessing values added via DataBinder.Eval()
 ? Repeater databinder.eval double quotes
 ? Remove DataBinder.Eval field if it is null or blank
 ? DataBinder.Eval data item Empty
 ? Print Empty String when DataBinder.Eval is NULL
 ? Can't bind Visible property
 ? Jackson Boolean and Array Data binding