ASP.NET Repeater not binding after ItemCommand

…衆ロ難τιáo~ 提交于 2019-12-24 07:48:33

问题


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.



来源:https://stackoverflow.com/questions/4054587/asp-net-repeater-not-binding-after-itemcommand

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!