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

不打扰是莪最后的温柔 提交于 2019-12-06 08:38:33

问题


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?


回答1:


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(); }
}


来源:https://stackoverflow.com/questions/979840/asp-net-bind-a-value-to-a-custom-user-control-inside-a-repeater

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!