ASP.NET: Bind a value to a custom user control inside a repeater

asp.netrepeater

I have an ASP.NET control that binds data to a repeater. Inside that repeater, I have another custom user control. I want to pass a value to this second control based on the current binding item.

<asp:Repeater runat="server" ID="ProductList">
    <ItemTemplate>
        <p>Product ID: <%# Eval("ProductID") %></p>
        <myControl:MyCoolUserControl runat="server" ProductID='<%# Eval("ProductID") %>' />
    </ItemTemplate>
</asp:Repeater>

The repeater item template correctly prints out my Product ID with the Eval statement, but when I do the same thing to pass the Product ID to MyCoolUserControl, it doesn't work (if ProductID on MyCoolUserControl is a Nullable Int32 – I can debug it and it's always null).

Any ideas how I can do this?

Best Answer

I did a small test and I got it working if the ProductID is a string. After I changed it to and int in the usercontrol I got kind of the same problems. I did a int.Parse in the datasource to the repeater and got it working again. Check to see that the ProductId that you pass into the repeaters datasource is of type int.

Mytest app.

string[] values = new string[]{ "12", "13" };

MyRepeater.DataSource = from v in values
                        select new
                        {
                            ProdId = int.Parse(v)
                        };

MyRepeater.DataBind();

<asp:Repeater runat="server" ID="MyRepeater">
    <ItemTemplate>
        <My:control runat="server" ProductId='<%# Eval("ProdId") %>' />
    </ItemTemplate>
</asp:Repeater>

and in the usercontrol:

public int? ProductId
{
    set { MyLabel.Text = value.Value.ToString(); }
}
Related Topic