1

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?

Programer
  • 965
  • 3
  • 20
  • 45

1 Answers1

0

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.

Martin Braun
  • 5,873
  • 7
  • 43
  • 81
  • Thank you. I did what you suggested, I now have a repeater called "ProductsArea", I use ProductsArea.DataSource = Products; ProductsArea.DataBind(); in the code behind, and in the front I use: . But the Item is always null in my control. Why is this. – Programer Dec 09 '14 at 09:33
  • @Programer Never used the `Repeater` control by myself. How about setting the `ItemType` of the `Repeater` to the full namespace + type of `Product` and then use `` as seen here: http://stackoverflow.com/a/17328960/1540350 Hope this works. Or try ``. Please try all the answers here: https://stackoverflow.com/questions/5011617/asp-net-repeater-bind-liststring and give me feedback what worked. – Martin Braun Dec 09 '14 at 10:28