Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top