在运行时将数据绑定到中继器
本文关键字:中继器 数据绑定 运行时 | 更新日期: 2023-09-27 17:53:03
我有一个在运行时将数据绑定到重复器控件的问题,我知道如何在aspx中绑定数据,但无法弄清楚如何在运行时这样做。我有未知数量的行要绑定,每一行都有未知数量的项,这个结构是一个列表的列表,我把它分配给后面代码中的中继器数据源。但是要得到我想要的格式,我应该写什么,而不是这个代码在ItemDataBound事件后面的代码?
<asp:Repeater ID="RepeaterCategories" runat="server" OnItemCreated="RepeaterCategories_ItemCreated" OnItemDataBound="R1_ItemDataBound">
<ItemTemplate>
<asp:LinkButton ID="parent1Link" runat="server" ForeColor="#570000" CommandArgument='<% #Eval("ParentID1") %>'
Text='<% #Eval("ParentName1") %>' Font-Size="Small" Font-Underline="False" Font-Bold="True"
Font-Names="Arial" PostBackUrl='<% #CategoryId(Eval("ParentID1")) %>'>
</asp:LinkButton>
<asp:Image ID="Image3" runat="server" Width="7px" ImageUrl="~/Img/next.png" />
</ItemTemplate>
</asp:Repeater>
下面是你应该做的一个例子:
您的aspx页面
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
<ItemTemplate>
<li>
<img id="imgArticle" runat="server"><p>
<a href="#" id="aTitle" runat="server"></a>
</p>
<span class="grey">
<asp:Literal ID="litCountry" runat="server"></asp:Literal>
<asp:Literal ID="litTime" runat="server"></asp:Literal>
</span></li>
</ItemTemplate>
</asp:Repeater>
绑定中继器:
rpt.DataSource = articles; // articles is a Generic List which has data
rpt.DataBind();
on Item databound:
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var item = (Article)e.Item.DataItem;
if (item.Title != null)
((HtmlAnchor)e.Item.FindControl("aTitle")).InnerText = item.Title;
if (item.Country != null)
{
if (item.Country.Length > 0)
((Literal)e.Item.FindControl("litCountry")).Text = item.Country + " ,";
}
((Literal)e.Item.FindControl("litTime")).Text = item.CreationDate.ToString();
}
}
如果你有一个特别复杂的安排,你有几个选择。你可以使用带有自动生成列的GridView,并使用OnItemDataBound来微调。当然,您也可以直接将原始HTML输出到DIV中。