How to access the item being data bound during ItemDataBound?

Ian Boyd picture Ian Boyd · Dec 5, 2008 · Viewed 34.9k times · Source

I want to get at the item that is being data bound, during the ItemDataBound event of an asp:repeater.

I tried the following (which was an unaccepted answer in a stackoverflow question):

protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    Object dataItem = e.Item.DataItem;
    ...
}

but e.Item.DataItem is null.

How can I access the item being data bound during the event called ItemDataBound. I assume the event ItemDataBound happens when an item is being data bound.

I want to get at the object so I can take steps to control how it is displayed, in addition the object may have additional helpful properties to let me enrich how it is displayed.

Answer

Tool had the right answer. The answer is that e.Item.Data is only valid when e.Item.ItemType is (Item, AlternatingItem). Other times it is not valid. In my case, I was receiving ItemDataBound events during header (or footer) rows, where there is no DataItem:

protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
   // if the data bound item is an item or alternating item (not the header etc)
   if (e.Item.ItemType != ListItemType.Item && 
         e.Item.ItemType != ListItemType.AlternatingItem)
   {
      return;
   }

   Object dataItem = e.Item.DataItem;
   ...
}

Answer

Programmin Tool picture Programmin Tool · Dec 5, 2008

Right off the bat I would have to guess you need this:

if (e.Item.ItemType == ListItemType.Item ||
    e.Item.ItemType == ListItemType.AlternatingItem)
{
    //Put stuff here
}

After all, the item itself could be representing a header or footer row.