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
Placeholderand populate it in code behind, or (even better) use theRepeatercontrol that takes your ProductList and builds yourproductBoxes.So in the
ItemTemplateof yourRepeateryou should put yourProductBoxand use<%# (Product)Container.DataItem %>expression on yourItemproperty like binding a simple list to aRepeater.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.