Why is DataItem always null in the Page_Load handler?
I've created an ASP.net web page with an ASP Repeater. I bind the ASP Repeater with an IOrderedEnumerable<int>
DataSource.
I need to access the Repeater DataItems at inside the Page_Load event handler. However, when I try to get the value of repeater.Items[x].DataItem
, I 开发者_如何转开发always get null. There should always be an integer value here.
In spite of this, the page otherwise renders fine. Why can't I access the DataItem
property of my RepeaterItems inside the Page_Load event handler?
Your Repeater
doesn't databind until later in the page lifecycle. If you want to reference Repeater.Items[i].DataItem
in a Page.Load
handler, try to early-bind the Repeater
first:
repeater.DataBind()
Its only available during databinding.
As everyone else has said, it's only available during databinding. You will need to wire up the OnItemDataBound event of the repeater. In its event handler, you can do this:
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
switch (e.Item.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
WhateverType Item = e.Item.DataItem as WhateverType;
break;
}
}
The data items only exist after the databinding process has taken place. The only thing that is preserved across postbacks in the repeater are the control properties that are serialized in viewstate. If you need the data in those items, you can do like pseudocoder said and databind earlier or if that is not possible you could write a utility function that takes a repeater data item and extracts it from the controls in your repeater (assuming you stored all the information you need in those controls somehow)
精彩评论