ASP.NET Repeater not binding after ItemCommand

2019-08-05 14:05发布

问题:

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 items 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

回答1:

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.