Wednesday, March 5, 2008

Where's My DataItem?

One of the most commonly-used patterns when developing with ASP.NET's data-bound controls is the idea of catching the control's RowDataBound or ItemDataBound event and customizing the display of that row/item in some way based on the data in the underlying data item:


protected void grdBallots_RowDataBound ( object sender, GridViewRowEventArgs e )

{

    
if ( e.Row.RowType == DataControlRowType.DataRow )

    {

        
DataRowView rowView = ( DataRowView ) e.Row.DataItem;



        
if ( rowView != null )

        {

            
// ...do customizations here...

        }

    }

}



One of the new server controls that is part of the recent v3.5 release of the .NET Framework is the ListView control. This control combines the templated flexibility of the older Repeater control with the power and ease of use of the GridView control. However, the first time you attempt to use the technique above to customize the way a particular item is displayed, you will notice that the ListViewItem object (obtained in the ItemDataBound event through the ListViewItemEventArgs.Item property) does not contain a reference to the DataItem. So how do you get a reference to the DataItem?

It turns out that an extra object layer has been added to the ListView control's class hierarchy:


protected void lvwFiles_ItemDataBound ( object sender, ListViewItemEventArgs e )

{

    
if ( e.Item.ItemType == ListViewItemType.DataItem )

    {

        
ListViewDataItem dataItem = ( ListViewDataItem) e.Item;

        
DataRowView fileData = ( DataRowView ) dataItem.DataItem;



        
if ( fileData != null )

        {

            
// ... do your customization here...

        }

    }

}



So there you go!