repeater的e.item.dataitem为null问题
页面: <asp:Repeater runat="server" ID="rpt" OnItemDataBound="rpt_ItemDataBound">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chk" />
</ItemTemplate>
</asp:Repeater>
代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Model.Users> list = new DAL.Users().GetList();
rpt.DataSource = list;
rpt.DataBind();
}
}
protected void btn_Click(object sender, EventArgs e) //统计按钮
{
int cnt = 0;
foreach (RepeaterItem ri in rpt.Items)
{
if (ri.ItemType == ListItemType.Item)
{
Model.Users m = ri.DataItem as Model.Users;//这里运行为NULL
if (m.Xb == "男")
cnt++;
}
}
}
问题1:运行Model.Users m = ri.DataItem as Model.Users后,m为null,不知道什么原因?怎么解决?为什么在ItemBound时间中可以使用Model.User m = e.Item.DataItem而且可以获得值,在btn事件中为什么不可以?
问题2:if (ri.ItemType == ListItemType.Item)为什么不写也可以,HeaderTemplate为什么没有被计入到rpt.Items中?
谢谢。
------解决方案--------------------
------解决方案--------------------
上面描述不太正确
rpt.Items应该是不计入HeaderTemplate的
只包含数据绑定的项
Item和AlternatingItem
从Reflector代码看
RepeaterItemCollection Items属性是通过
this.itemsCollection = new RepeaterItemCollection(this.itemsArray);
生成的
而itemsArray代表的是数据项
C# code
if (this.itemsArray != null)
{
this.itemsArray.Clear();
}
else
{
this.itemsArray = new ArrayList();
}
if (!useDataSource)
{
dataItemCount = (int) this.ViewState["_!ItemCount"];
if (dataItemCount != -1)
{
data = new DummyDataSource(dataItemCount);
this.itemsArray.Capacity = dataItemCount;
}
}
else
{
data = this.GetData();
ICollection is2 = data as ICollection;
if (is2 != null)
{
this.itemsArray.Capacity = is2.Count;
}
}
if (data != null)
{
int itemIndex = 0;
bool flag = this.separatorTemplate != null;
dataItemCount = 0;
if (this.headerTemplate != null)
{
this.CreateItem(-1, ListItemType.Header, useDataSource, null);
}
foreach (object obj2 in data)
{
if (flag && (dataItemCount > 0))
{
this.CreateItem(itemIndex - 1, ListItemType.Separator, useDataSource, null);
}
ListItemType itemType = ((itemIndex % 2) == 0) ? ListItemType.Item : ListItemType.AlternatingItem;
RepeaterItem item = this.CreateItem(itemIndex, itemType, useDataSource, obj2);
this.itemsArray.Add(item);
dataItemCount++;
itemIndex++;
}
if (this.footerTemplate != null)
{
this.CreateItem(-1, ListItemType.Footer, useDataSource, null);
}
}