简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM