Databinding a List to a usercontrol in an Item Template in codebehind

霸气de小男生 提交于 2019-12-08 06:31:59

问题


I have a DataList like below:

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

The Item Template is simply a registered usercontrol, MyControl. The DataSource for the DataList is a List<List<T>> and MyControl's PublicProperty is passed List<T> which it then peforms its own databinding on. This works fine, but I have a general aversion to databinding in the aspx/c page. What is the most efficent way to set the PublicProperty value in the code behind?


回答1:


If in line data binding syntax is not good enough for you - you can always hook into the ItemDatabound event of the DataList.

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

Then, in the code behind of your page/containing control you can add your ItemDataBound event.

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

For more information on the DataList.ItemDataBound event - Read Here

If you would rather not declare your ItemDataBound delegate inline in the ASPX you could also do it in the code behind - probably in your Page Load event:

myDataList.ItemDataBound += DataList_ItemDataBound;

Hope that helps



来源:https://stackoverflow.com/questions/1207147/databinding-a-list-to-a-usercontrol-in-an-item-template-in-codebehind

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