简体   繁体   中英

Why is e.Item.DataItem null on ItemDataBound event when binding an asp:net Repeater to a Collection?

I'm trying to bind a collection implementing the ICollection, IEnumerable and IList interface to an asp.net repeater. The Collection is named CustomCollection. So I'm setting the datasource of the repeater to the collection, as follows:

rptRepeater.DataSource = customCollection;
rptRepeater.Databind();

Then, on the ItemDataBound event, I'm trying to access the DataItem object, as follow:

void rptRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e){

object obj = e.Item.DataItem; // DataItem is null for some reason

}

For some reason the e.Item.DataItem object is null. Do anyone know why this is, and/or what I could do to get hold of the object in the collection that is to be databound to the repeater?

Thanx!

In your ItemDataBound event handler, you need to check that it is not trying to bind to a header or footer template:

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
    object obj = e.Item.DataItem;
}

你也可以使用:

if(e.item.dataItem != null) object obj = e.Item.DataItem;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM