0
votes

I have a datalist and I'm trying to apply a css class to a panel inside some of the items like so:

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? Can someone please explain this to me?

1
I've tried that but it simply selects the previous item or gives another error if the item was the first one.. - Lambusy
Is the exception is being raised service.GetProduct(...) or at some other line. Can you share this method too. - Suprabhat Biswal
service.GetProuct() returns a dataset with a single row through a primary key, the exception isn't raised there - Lambusy

1 Answers

0
votes

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.