在Codebehind中的项目模板中将列表数据绑定到用户控件 [英] Databinding a List to a usercontrol in an Item Template in codebehind

查看:102
本文介绍了在Codebehind中的项目模板中将列表数据绑定到用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataList如下:

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>

项目模板只是注册的用户控件MyControl。 DataList的DataSource是一个 List< List< T> 和MyControl的PublicProperty被传递 List< T> 然后它会自己编写数据。这工作正常,但我在aspx / c页面中有一个一般的数据绑定。在代码中设置PublicProperty值的最有效方法是什么?

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?

推荐答案

如果在线数据绑定语法对你来说不够好 - 你可以随时钩入DataList的ItemDatabound事件。

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>

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

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

有关DataList.ItemDataBound事件的更多信息 - a href =http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound.aspx =nofollow noreferrer>阅读此处

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

如果您不想在ASPX中内联自己的ItemDataBound代理,您还可以在代码中执行此操作 - 可能在您的Page Load事件中:

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;

希望有帮助

这篇关于在Codebehind中的项目模板中将列表数据绑定到用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆