15

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?

Fermin
  • 34,961
  • 21
  • 83
  • 129

4 Answers4

23

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.

George Stocker
  • 57,289
  • 29
  • 176
  • 237
Adam Nofsinger
  • 4,004
  • 3
  • 34
  • 42
4

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.

KOTJMF
  • 991
  • 1
  • 7
  • 17
1

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;
    }
}
benscabbia
  • 17,592
  • 13
  • 51
  • 62
1

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")))%>
Fermin
  • 34,961
  • 21
  • 83
  • 129
  • 1
    I like this solution better than catching it on the ItemDataBound event. The only suggestion is that within your method `doFormatting` you should check for `null` or `DBNull` – p.campbell Nov 19 '09 at 22:44