gpt4 book ai didi

c# - asp.net Repeater - 获取对当前项目的引用

转载 作者:行者123 更新时间:2023-11-30 12:59:03 25 4
gpt4 key购买 nike

我正在使用 Asp.net 4.5,C#。我有一个绑定(bind)了一些 DataSource 的 reapter:

  <asp:Repeater ItemType="Product" ID="ProductsArea" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
...
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>

在这个转发器中,我想要一个对当前迭代项的引用。我知道我可以使用 <%#Item%>我可以使用 <%#Container.DataItem%> .如果我想到达一个字段,我可以使用 <%#Item.fieldName%>或评估它。

但是我想在一个字段上设置一个条件,我怎样才能得到对#Item 的引用以便做这样的事情:

<% if (#Item.field>3)%>, <%if (#Container.DataItem.field<4)%> 

我想 acautley 想要这样的引用 <%var item = #Item% > 而不是在我需要的时候使用它。

当然上面的语法是无效的,如何实现这个properley?

最佳答案

我会改用 ItemDataBound。这使代码更具可读性、可维护性和健壮性(编译时类型安全)。

protected void Product_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// presuming the source of the repeater is a DataTable:
DataRowView rv = (DataRowView) e.Item.DataItem;
string field4 = rv.Row.Field<string>(3); // presuming the type of it is string
// ...
}
}

e.Item.DataItem 转换为实际类型。如果您需要在 ItemTemplate 中查找控件,请使用 e.Item.FindControl 并适本地转换它。当然你必须添加事件处理程序:

<asp:Repeater OnItemDataBound="Product_ItemDataBound" ItemType="Product" ID="ProductsArea" runat="server">

关于c# - asp.net Repeater - 获取对当前项目的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401177/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com