【问题标题】:Databinding a List to a usercontrol in an Item Template in codebehind将列表数据绑定到代码隐藏中项目模板中的用户控件
【发布时间】:2009-07-30 14:55:21
【问题描述】:

我有一个如下所示的 DataList:

<asp:DataList runat="server" ID="myDataList">
   <ItemTemplate>
     <uc:MyControl ID="id1" runat="server" PublicProperty='<%# Container.DataItem %>' />
   </ItemTemplate>
</asp:DataList>

项目模板只是一个注册的用户控件,MyControl。 DataList 的 DataSource 是 List&lt;List&lt;T&gt;&gt;,而 MyControl 的 PublicProperty 传递给 List&lt;T&gt;,然后它会在其上执行自己的数据绑定。这很好用,但我对 aspx/c 页面中的数据绑定有普遍的反感。在后面的代码中设置 PublicProperty 值的最有效方法是什么?

【问题讨论】:

    标签: c# asp.net data-binding itemtemplate


    【解决方案1】:

    如果行内数据绑定语法对您来说不够好 - 您可以随时挂钩 DataList 的 ItemDatabound 事件。

    <asp:DataList runat="server" ID="myDataList" 
                    OnItemDataBound="DataList_ItemDataBound">
        <ItemTemplate>
            <uc:MyControl ID="id1" runat="server" />
        </ItemTemplate>
    </asp:DataList>
    

    然后,在页面/包含控件的代码中,您可以添加 ItemDataBound 事件。

        protected void DataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item
                || e.Item.ItemType == ListItemType.AlternatingItem)
            { 
                DataListItem item = e.Item;
                //List<string> or whatever your data source really is...
                List<string> dataItem = item.DataItem as List<string>;
                MyControl lit = (MyControl)item.FindControl("id1");
                lit.PropertyName = dataItem;
            }
        }
    

    有关 DataList.ItemDataBound 事件的更多信息 - Read Here

    如果您不想在 ASPX 中内联声明您的 ItemDataBound 委托,您也可以在后面的代码中进行 - 可能在您的页面加载事件中:

    myDataList.ItemDataBound += DataList_ItemDataBound;
    

    希望有帮助

    【讨论】:

    • 我希望得到一些不那么冗长的东西...myDataList.Controls[0].Controls[1].FindControl("control") 等。但由于这是唯一有效的答案,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多