简体   繁体   English

ASP .NET数据列表无法识别ItemDataBound事件中的项目

[英]ASP .NET datalist does not recognize item in ItemDataBound event

I have a datalist and I'm trying to apply a css class to a panel inside some of the items like so: 我有一个数据列表,我正在尝试将CS​​S类应用于某些项目内的面板,例如:

protected void DataListProducts_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType != ListItemType.Header)
    {
        ProductsService service = new ProductsService();
        DataTable dt = service.GetProduct(DataListProducts.DataKeys[e.Item.ItemIndex].ToString()).Tables[0];
        if (((int)dt.Rows[0]["Quantity"]) <= 0)
        {
            Panel overlay = (Panel)DataListProducts.Items[e.Item.ItemIndex].FindControl("overlay");
            overlay.CssClass = "soldOut";
        }
    }
}

When I try to run it I get the error 当我尝试运行它时,我得到了错误

"Index was out of range. Must be non-negative and less than the size of the collection." “索引超出范围。必须为非负数,并且小于集合的大小。”

I found out that the item index is equal to the item count of the datalist, which I think means the item hasn't been created yet, but shouldn't the ItemDataBound event fire after the item has been created and databound? 我发现项目索引等于数据列表的项目计数,我认为这意味着尚未创建该项目,但是在创建项目并进行数据绑定之后,是否应该触发ItemDataBound事件? Can someone please explain this to me? 有人可以向我解释一下吗?

Well, kinda solved it. 好吧,有点解决了。 I still don't know what the problem was, but iterating through the datalist with a foreach loop in a different function after the datalist has been databound gives me the desired effect. 我仍然不知道问题出在哪里,但是在数据列表被数据绑定之后,在另一个函数中使用foreach循环遍历数据列表可以达到预期的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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