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

1.9k views Asked by At

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?

1

There are 1 answers

2
Martin Braun On BEST ANSWER

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 productBoxes.

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.