简体   繁体   中英

Asp.net UserControl - How to Data-Bind objects from a list?

I am using asp.net 4.5 c#. I have created a user control with the following member inside:

  [Bindable(true)]
    public Product item
    {
        get{
            return _product;
        }
        set
        {
            _product = value;
        }

    }

I then use my control, while DataBinding a "Product" into the member above:

  <script runat="server">
Product item=new Product();
            </script>  
                    <uc:productBox runat="server" item="<%#item%>"/>      

While this works, Trying to bind dynamic items from a list in the following way fails:

  foreach (Product item in ProductList()){%>          
                    <uc:productBox runat="server" item="<%#item%>"/>       
            <%}%>

I get the following error:

The name 'item' does not exist in the current context

Why can't I bind items from a list and how can I solve this in order to work?

Binding expressions can only access variables in the scope of the class or static members from anywhere visible, not the scope of any loop as the loop will be executed in the own scope in code behind, in real.

You should rather use a Placeholder and populate it in code behind, or (even better) use the Repeater control that takes your ProductList and builds your productBox es.

So in the ItemTemplate of your Repeater you should put your ProductBox and use <%# (Product)Container.DataItem %> expression on your Item property like binding a simple list to a Repeater .

A small hint: Building foreach in the ASPX is not very well written. Never do that. Also the name convention insists to start with upper case letters on class / control / public member names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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