Using the ItemDataBound event with a DataReader vs DataTable/DataView
A little while back I was blogging about how we were switching over to datareaders for getting data back from our database. Well it was working fine until we noticed on some of our pages data wasn't being calculated correctly. This was traced to the ItemDataBound event used in our grids/repeaters not working correctly. With a datatable/view we would cast the e.Item.DataItem as a DataRowView; which works just fine. However datareaders when being databound can't be cast as DataRowViews. You have to use the DbDataRecord class. Afte switching from the DataRowView to DbDataRecord in the ItemDataBound event everything works just like it should. DbDataRecord is in the System.Data.Common namespace. Make sure you are importing that namespace if you haven't already.
So to summarize it:
Binding Object | What to Cast to in ItemDataBound event |
DataReader | DbDataRecord |
DataTable | DataRowView |
DataView | DataRowView |
Comments
DbDataRecord belongs in the System.Data.Common namespace for those who haven't imported it.