开发者

ASP.NET Repeater not binding after ItemCommand

I have a repeater that is looping a user control, like this:

                <asp:Repeater ID="repItems" runat="server" EnableViewState="false" 
                OnItemCommand="repItems_ItemCommand">
            <ItemTemplate>
                <dmg:confirmItem runat="server" 
                OnDataBinding="confirmitemItem_DataBinding"  
                Basket="<%# Container.DataItem %>" />
            </ItemTemplate>

            </asp:Repeater>

My code behind looks like this:

  public void BindItems(List<ShopBasket> baskets)
    {
        _baskets = baskets;
        repItems.DataSource = baskets;
        repItems.DataBind();
    }

My custom user control looks like this:

public ShopBasket Basket;
        protected void Page_Load(object sender, EventArgs e)
        {

            imgItem.ImageUrl = ShopImagePath + Basket.ImageFilename;
            ...etc...
        }

All works brilliantly the first time around, the basket 开发者_如何学Goitems are bound to Basket objects and everything is great.

However, when I receive an ItemCommand from my repeater, and update the basket contents (Note: No adding or removing is done here, just updates the quantity) then I rebind to see the latest values, and BOOM! Null reference - no Basket object in the user control Page_Load. This is despite tracing through to see that the BindItems() method is called as usual, and the Baskets are there.

I presume this has something to do with the life cycle but it has me beat.

Any ideas?

Thanks Duncan


It's a little dangerous to have a public field store an item being bound, especially when you have multiple items. A safer way to do it is to extract the Basket as the DataItem bound to the repeater, and do something with it that way in the repeater ItemCommand event. ItemDataBound would be even safer as you know the basket would be existing (since it's data bound), Page_Load is not a safe option here...

HTH.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜