views:

452

answers:

1

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?

+3  A: 

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

Gavin Osborn
have updated my code... was an error in the ItemType logic
Gavin Osborn
I was hoping for something much less verbose...myDataList.Controls[0].Controls[1].FindControl("control") etc. But since this is the only answer that does work, thanks.
Nick